Welcome to the deep dive. Today, we're taking a really focused look at JavaScript, specifically for web developers. We're pulling everything from this one pretty comprehensive book. But hey, even if you're not a coder, stick around. Yeah, definitely understanding JavaScript basics. It's kind of like getting a peek under the hood of you know, all those interactive websites who use every single day exactly.
Think of it as uncovering the essential mechanics our source. It's aimed at web developers, but the core ideas right, and you know some of the let's say, surprising ways JavaScript works. That's interesting for anyone curious about webtech.
So our mission today is well, pretty straightforward but important. Yeah, pull out the key building blocks of JavaScript, demystify how it makes websites actually do things, and hopefully you'll have a few of those aha.
Moments we should. The book covers a lot, from basic syntax writing the code, to making page elements react, even server communication loads to cover.
Let's just dive right in chapter one the basics.
Okay, so first off, the book really emphasizes using the browser's developer tools, specifically the console. Ah.
The console.
Yeah, it can look a bit intimidating candidate, it.
Can, but it's actually a fantastic place to just try stuff out, like a sandbox.
Okay. The book gives an example, right like three plus five.
Yep, type three plus five hit ender and boom eight. Makes perfect sense.
But then it shows console dot log hello, and that gives you hello, but then also undefined. Okay, what's up with the undefined there? Why does that show up?
Well, it's about what console dot log is designed to do. Its main job is to display something like the text hello, okay, and it does that, but the function itself doesn't really return a useful value back to the program in the way three plus five returns eight.
Ah.
I see.
So in JavaScript, if a function doesn't explicitly say return this value, it just automatically returns undefined.
So console dot log does its job displaying hello, but the result of running the function is just nothing useful, hence undefined.
Exactly like think of a printer at printer document, right, but the act of printing itself doesn't like create a new document as its output.
It just performs the action that printer analogy actually helps a lot.
Okay, action versus result.
Got it, and the book also sets the stage, you know, explaining that JavaScript is basically just text plain text files, right, and.
The browser reads those files and interprets the instructions.
Yeah, it executes the code. And these files are made up of statements individual instruction.
Like console do log Hello, that's one statement precisely.
And you can group statements together in blocks using curly braces, sometimes optional for single lines, but the book uses them consistently for clarity.
Good practice probably, And semicolons.
At the end of statements. The book says they're often optional if you use line breaks.
Yeah. JavaScript tries to be clever and insert them. Sometimes it's called automatic semicolon.
Insertion, but the book uses them anyway.
It does for consistency and to avoid you know, potential weird edge cases where the automatic insertion might guess wrong. It's generally seen as safer.
Okay, good to know. Then variables super fundamental.
Absolutely. Think of them as labeled boxes storage locations in memory.
And you use the equals sign the assignment operator to put something in the box.
Right, the book uses a three, then plus one, then console dot log.
Which shows four, so you put three in a set. Then you take what's an eye, which is three, add one, and put the result four back into exactly that.
A plus one looks a bit strange mathematically, but it's standard in programming. Update the variable based on its current value.
And for those common plus one and opus one operations, there are shortcuts.
Yep, the increment plus plus and decrement operators just shorthand for adding or subtracting one very common.
And there are other assignment shortcuts too, like plus.
Rate plus a ten is just a shorter way to write A plus.
Ten makes sense, like the example A five plus equals ten results in fifteen. Keeps the code a bit tidier.
It does, especially when things get more complex, saves it. A typing makes the intent clear once.
You know them now, something that can trip people up.
Case sensitivity, oh yeah, hugely important to JavaScript.
The book stresses that thing with a lowercase T is totally different from thing with an uppercase.
T, completely different variables as far as JavaScript is concerned, and that difference it can lead to some really really hard to find bugs.
Because you defined it one way and try to use it another and suddenly it's undefined or not what you expect exactly.
You've got to be precise with spelling and capitalization like library call numbers.
Okay, how do we actually declare these variables? The book introduces var, let, and const.
Right. So var is the older way if you just say var my variable. Its initial value is undefined.
Until you assign something to it, yep.
Whereas let and const are newer constants or values you don't intend to change later.
Constants you have to give a const of value when you declare it, right. You can't just say const x correct.
Yeah, you can't reassign it later either. Lit is for variables that you do expect to change.
And var it has some quirks, something about hoisting.
Yeah. Var declarations get sort of mentally moved to the top of their scope by the JavaScript engine. It can sometimes cause confusing behavior if you're not aware of it.
Whereas let and const don't do that.
They have what's called block scope exactly.
They're generally considered safer and lead to fewer surprises. The book also warns about just using variables without declaring them at all.
Oh right, in non strict mode.
Yeah, JavaScript might just create a global variable for you, which is usually a bad idea can cause conflicts and bugs.
So always declare your variables, use let or const preferably.
That's the modern best practice.
Yes, okay, to keep code readable, we use.
Comments crucial for single line comments and followed by for multiline comments. Yeah. Great for explaining why you did something or for temporarily disabling code during testing. Just remember you can't nest the multi lined comments.
Good tip.
And finally for this section, strict mode.
Ah, yes, you strict You put that string is the very first thing in your script or the top of a function.
And what does it do? Make JavaScript stricter?
Pretty much? It tells the browser, hey, be less forgiving about errors and enforce stricter rules.
So it catches potential problems that regular JavaScript might just.
Ignore exactly, things that are considered bad practices or ambiguous code. Strict mode often turns those into actual errors, making them easier to find and fix. Highly recommended for new code.
Right helps you write cleaner, more reliable code from the start.
Okay, Moving on from the basics of writing code, the book gets into the actual types of data. JavaScript works with data types. Right starts with numbers, and the key thing here is that JavaScript doesn't really distinguish between whole numbers, integers, and numbers with decimal points floating point number. It's calls of all number yep one single number type, which leads us to a classic.
Issue ah the point one plus point two problem.
The very same console dot log zero zero zero zero zero zero zero zero doesn't give you point.
Three, it gives you point three zero zero zero zero zero zero zero zero zero zero zero zero zero zero zero zero zero zero zero zero zero zero zero zero zero zero zero zero zero zero zero four are something ridiculously long.
Like that exactly. It's because computers use binary base two internally, and just like thirteens that are repeating decimal in our base ten system, some simple base ten fractions don't have an exact finite representation in binary.
So tiny rounding errors creep. In the book mentions this isn't just a JavaScript thing, right.
No, it happens in many languages. JavaScript just doesn't hide it as much. It's something to be aware of, especially if you're doing precise financial calculations for example good point.
So, besides that quirk, you can write numbers normally with decimals or using exponential notation like one point two three E four four twelve fo hundred.
Right and briefly it mentions binary notation with zero bo okay.
Then operators for numbers we saw, but the arithmetic ones.
The usual suspects plus for edition, subtraction, multiplication, division.
And the crucial part operator precedence the order they happen in.
Yes, just like math class parentheses first, then multiplication and division, then addition and subtraction.
And if they have the same precedence like Warren.
Evaluated left to right. The books example twelve to two to three really shows this right.
It's twelve two which is six, then sixty three which is eighteen, not twelve two three exactly.
Understanding precedents avoids surprises.
And there's the remainder operatorcent shit, the.
Percent sign one hundred perc seven gives you two because one hundred divided by seven is fourteen with the remainder of two.
And the book says it's useful for things like cyclic patterns.
Yeah, figuring out days of the week, or maybe alternating styles in a list, anything where you need to know the remainder after division, or just checking if a number is even or odd number percent two okay.
Next, data type strings text.
Sequences of characters. You enclose them in either single quotes or double quotes.
The book uses single quotes mostly, but the console often shows double yeah.
Either's fine. Just be consistent within a project, and importantly use the straight quotes, not the curly typographic ones. Some word processors like to.
Use gotcha, and a key property of strings immutable.
Yes. Immutable means once a string is created, you cannot change its contents directly.
So I five Hello and I want jello. I can't just swap the H.
For a J.
Nope. Any operation that seems to modify a string actually creates a brand new string in memory with the changes. The original Hello is untouched.
Okay. Good to know, especially for performance. If you're doing lots of string changes.
It can be yeah. The book also mentions escape characters using the backslash.
Right, like if you want a single quote inside a single quoted string.
Don't exactly or end for a newline character T for a tab, et cetera.
And joining strings together concatenation.
Just use the plus operator. Hello plus plus world gives you Hello World.
Careful if you mix strings and numbers, very careful.
Five plus ten is fifteen, but five plus ten is five to ten. JavaScript sees the string and decides to do concatenation converting the number ten to the string ten.
Ah.
Okay, potential, gotcha.
There definitely strings also have built in properties and methods. The book mentions.
Length absdef dot length would be six easy.
Enough, yep. And then parcent and pars float for converting strings to numbers.
Right, so parsent one two three gives the number one twenty three? What about parsent one towiny three guys.
Still gives one twenty three? It reads the numbers from the start until it hits a non numeric character.
And parcent reygo ze one two three.
That would return nan, not a number, because it couldn't find any valid number at the very beginning.
Okay, so nan is this special value indicating an invalid number?
Result exactly, and there's a function is nan to specifically check if value is nan useful.
The book also quickly mentions booleans.
True and false the logical values fundamental for decisions in statements loops.
Though not much detail in this chapter. And then null and undefined.
Right two ways of representing nothing. Null is usually an intentional assignment of no value, like saying this variable should currently hold nothing.
Whereas undefined often means it hasn't been given a value.
Yet, often yes, or it's the default return value from a function that doesn't explicitly return anything crucially undefined itself isn't an error.
State, just means no value assigned.
Okay, all right?
That leads nicely into functions.
Reusable blocks of code. The book gives an example of function twice in return number two.
Yeah, so twice is the function name. Number inside the parentheses is a parameter, a placeholder for the input.
And when you call it like twice five, the five is the argument passed in exactly, The.
Value five gets assigned to the number parameter inside the function for that specific call, and the return keyword that specifies the value the function should output or send back. It also immediately stops the function's.
Execution, so twice five would return ten.
Correct. And here's the connection back to undefined. If a function doesn't have a return statement, or if it reaches the end without hitting.
One, it implicitly returns undefined, just like console dot log.
Precisely, all functions return something if you don't specify it's undefined.
Okay, makes sense now. The book briefly touches on those pop up dialogue boxes alert prompt confirmed.
Yeah, the old school ways to interact directly alert shows a message, prompt asks for text input, confirm asks the yes no question.
But they're kind of limited, right They block everything else totally.
They freeze the browser until the user interacts, and you can't style them. Modern web apps use better techniques, like Htmail's dialogue element, but the book uses these for simplicity in early examples.
Gotcha, Now, how does this JavaScript code actually get onto a web page?
Two main ways described Inline scripts You put your JavaScript code directly inside script tags within your htmail.
File file, often in the head section often yeah.
Or the second way, external scripts, You put your code in a separate JS.
File and link to it from the ADSTML using script src pathworre your script adscript.
Exactly and a crucial point. If a script tag has a src attribute pointing to an external file, any code you write between the opening and closing script tags is ignored.
Okay, so it's either in line or external with src, not both in the same tag.
Correct, And the scriptags can have other attributes type textuscript used to be commer but it's mostly default.
Now what about async and defer ah?
Those control how the script loads and runs relative to the HTML page being parsed. By default, when the browser hits a script tag, it stops parsing, HTML, downloads the script, runs it, and then continues parsing. This can slow down page rendering.
Right makes the page feel slow to load.
ACYNC tells the browser download the script in the background while parsing and run it as soon as it's downloaded, which might interrupt parsing briefly. Order isn't guaranteed if you have more ultiple ACNC scripts and defer. Defer also downloads in the background, but it guarantees the script will only run after the HTML parsing is completely finished and in the order the Defer scripts appear in the HTML.
So defer is often preferred for scripts that need the whole page structure to be ready.
Generally yes, especially for scripts that manipulate the page content. The book also mentions cross.
Origin right for loading scripts from different domains can cause issues if you're testing locally without a web server.
Yes, browsers have security rules about that. You might need to remove frosts origin anonymous if you're just opening HTML files directly from your computer, okay.
Error handling JavaScript used to be quiet about errors.
Historically, yes, sometimes things would just break silently, making debugging and nightmare.
But strict mode helps immensely.
It makes JavaScript throw more explicit errors for common mistakes, much better for catching bugs early.
And the book provides a basic template comments strict mode, and.
A simple window a function. It's like a safety net. If any uncaught error happens, this function runs and the template just uses alert to display the error message. Very basic, but a.
Starting point okay, that covers the foundational theory. Chapter two jumps into a project YEP.
A simple number guessing game, putting the basics into practice.
Starts with HTML just a button with egged start.
Game right, and the JavaScript uses document dot query selector button Halftag's start game to grab that button.
Query selector is the modern way using CSS selector exactly.
Hashtag start game means find the element with the id start game. Very powerful, and then.
It attaches an on click listener, so when you click the.
Button, it runs the play game function. That function contains the game's logic.
How does it get the user's guess using prompt again.
Yes, prompt guess a number. Remember Prompt returns the typed string an empty string or null if they cancel right.
And the game needs to check if the guess is right, too high, or too low using if statements yep.
If guess answer too low. So on basic conditional logic and.
To let the user keep guessing, a loop a do.
Wile, loop dot do bake it's guests give feedback. Wild guests answer the do.
Dot wile runs the code inside the do block at least once before checking the condition.
Correct, which makes sense here. You always want the user to make at least one guess.
And the book stress is testing trying different inputs.
Crucial test guessing too high, too low, the right number, canceling the prompt, entering non numbers. See how it behaves.
To get the secret number, it uses math dot random.
Yeah, that gives a random decimal between zero and almost one.
So you need to scale it and make it a whole number.
Right, You multiply by the maximum number you want example max, usemath dot floor to top off the decimal part and then add one to get range from one to max.
And the book puts this logic into a reusable.
Function exactly function random max retunemath dot floor math lot ran plus one. Good practice to encapsulate logic like.
That, and it warns you could accidentally overwrite built in functions if you name yours the same, like if you called your function math dot random.
Well, not quite math dot random because math is an object. But if there was a global random function, Yeah, naming collations can happen, so choose descriptive names.
Okay, what about when the user clicks cancel in the prompt it returns null. How does the game handle that gracefully?
Using the oer operator for default values like let guess prompt guests zero.
Ah, So if prompt returns null, which is falsey, the operator makes guests become zero instead.
Exactly prevents trying to compare null to a number later, which would cause errors.
Nice trick. Then organizing code, putting random into a separate library dot js file.
Yep, creating a function library for reusable code.
Good structure at comments, link it in the HTML with scripts src scriptslibrary, dot.
Js and remember that cross origin attribute again if testing locally right?
And the chapter ends by summing up comments, organization, loops, conditional.
Dialogues, all applied in a simple working game.
Okay.
Chapter three and moves into manipulating the web page itself, the DOM.
The document object model super important. It's the browser's internal representation of the HTML page like a structured tree, and JavaScript.
Can interact with this tree change things absolutely.
That's how you make pages dynamic. First step is finding the elements you want to change.
We saw document dot. Query selector already finds the first match for a CSS selector.
Yes, like query selector gets the first paragraph. Query selector hashtag my ideald gets the element with that id, Query selector dot my class gets the first element with that.
Class, and document dot.
Query selectoral that finds all matching elements and returns them as a collection a notalist.
So query selectoral gets you all the paragraphs on the page direct.
The book also mentions older methods like get element by eyed, get elements by tag name, get elements by.
Class name, less used now, but might see them in older code.
Pretty much. Query selector and query selectoral are generally or flexible because they use CSS selectors. Notice the elements plural, and the older ones often returned collections too.
Okay, So if qreer selectoral gives you a collection, how do you work with all those elements?
Two main ways shown A standard for loop using the length property of the noted list and accessing elements by index number. My nodalisty for the.
Four each method.
Yeah, often cleaner my nod list dot four each that uses an aero function as the callback. Okay.
Once you found an element, how do you change its content?
Two main properties dot text content and dot inner html.
What's the difference.
Text content gets or sets only the raw text inside an element, ignoring any HTML tags, and inner HTML gets or sets the entire HTML markup inside an element. If you set it, the browser parses the string as HTML.
The book warns about security with intern HTML. Right if the content comes from a.
User, big time. If a user can inject malicious HTML or script tags via inner HTML, it's a security rip. Cross site SCRIPTINGXSS. Use dots content whenever you just need to change text.
Got it?
Intertext is also mentioned, but text content is preferred.
Yeah. Text content has more predictable behavior regarding spacing and hidden elements.
Okay. What about changing attributes like the src of an image or the hrafh of a link.
Often you can access them directly as properties of the element object my image dot src e wal goals new dot jpg, my link, dot HRAF equals newpage dot HTML.
Simple enough. What about CSS classes?
There's the older dot class name property setting. It replaces all existing classes on the element with a new string.
You provide, which might not be what you want.
Usually not. The modern way is dot class list. It's an object with methods like dot.
Ad new class, dot remove old class, dot toggle active class exactly.
Toggle adds to the class if it's missing, removes it if it's present, and dot contains some class checks if the class exists. Much more precise control.
Why dot class name and class list. Why not do dot class.
Because class is a reserved keyword in Javacript, its self used for defining JavaScript classes, so they had to use slightly different names for the HTML attribute.
Ah okay. Now what if you want to create entirely new elements and put them on the page.
You use document dot create element. For instance, document dot create element creates a new carerograph element in memory.
It's not on the page yet not yet.
Then need to insert it somewhere. The book shows inserted Jason element position new element.
And the position can be like before begin, after begin, before and after end relative to an existing element.
Correct gives you fine grain control over where the new element goes.
There's also inserted Jason HTML.
Yeah, that's a shortcut. You give it the position and an HTML string. It purses the string and inserts the resulting elements directly. Convenient, but you don't get a direct reference to the newly created elements like you do with create element.
Key takeaway. Creating an element isn't enough. You have to explicitly add it to the dom to make it.
Visible absolutely from the metal.
All right.
Four applies this dom stuff to build a slide show.
Yeah. A practical example basic HTML, a DIFP container, maybe id slides and emptymg tag inside.
JavaScript links the library dot js from before and a new slideshow dot js.
And slideshow dot gs has the defer attribute on its script.
Deech, meaning it runs after the HTML is parsed. Library dot js doesn't have differ.
Right, implying the library needs to be ready earlier. Maybe because slideshow dot j as depends on functions in it. Yeah, and again that cross origin note For.
Local testing inside slideshow dot js, first step is grabbing the container dive and the MG element using query.
Selector standard practice get references to the elements you'll manipulate.
Then timing, set time out and set interval.
Setting out my function five thousand runs my function once after five seconds five thousand doll.
Second, and set interval.
My function two thousand runs my function repeatedly every two seconds exactly.
Set interval is key for the automatic slide changing.
So the basic slideshow logic have an array of image file names. You set interval to call a function every few seconds. That function updates the src attribute of the imag tag to the next file name in the array.
Right, you need a variable, say slide number, to keep track of which image index you're currently on and increment it each time. Looping back to zero.
At the end makes sense.
The book then suggests making the delay configurable.
Yeah, adding a delay parameter to the function that starts the slide show like does slides three thousand. Give it a default value too, So old code still works good for backward compatibility.
How do you stop and start it? Like a pause button?
Set interval returns a unique ID number. You store that ID in a variable. Okay, to stop it, you call clear interval the stored ID.
Ah, So a toggle function could check if the ID variable holds a number, meaning it's running. If yes, call clear interval and set the variable to null exactly.
And if the variables null it means it's starved, so you call set interval again to start it and store the new ID.
And you'd hook this toggle function up to a button using either dot on click or event listener click.
Tuggle sisely ad. Event listener is generally more flexible if you need multiple listeners on the same element to make.
It feel smoother. The book suggests prefetching the next image yeah.
While when image is showing, you create a new image object in JavaScript in the background like.
Let next image in a new image yep.
Then set it's src to the next slides url nextimage dot src images next line number. This tells the browser to start downloading it.
So when set interval fires and you actually change the main images src, the image data is likely already cashed.
Hopefully leading to a faster, smoother transition. Improves perceived performance. Cool.
What about keyboard control?
You can listen for keypresses on the whole document document dot on keypress sec event.
And the event object tells you which key is pressed yes.
The event dot keep property is the modern reliable way it gives you strings like body for spacebar, aerolaft, biahm, et cetera.
And you might use event dot prevent default, like to stop a space bar from scrolling the page if you're using it to pause play.
Exactly take control away from the browser's default action for that. Key errol functions work nicely here too, Document dot onkeypress event to make it more informative.
Add captions.
Yeah, change the images array instead of just file names, making an array of objects. Each object has image dot jpg caption a lovely photo.
So when you change the image, you update the mg dot src, but also find a caption element like p tag and set its dot text content.
Perfect, and also update the img dot alt and maybe mg dot title attributes for accessibility and tooltips.
Okay, so Chapter four summary timing, set time out, set interval, controlling intervals, clearinterval, event listeners on click at, event listener on keypress, and enhancing with prefetching and captions.
Putting dominipulation to work with timing and user interaction.
Chapter seven then shifts focus a bit, looking specifically at interacting with CSS and event listeners more deeply.
Right starts with a quick reminder CSS controls the visual appearance, colors, sponts, layout visibility, the.
Animations, and it mentions that CSS handles a lot more visual stuff now than it used to, less need for JavaScript for symple effects.
Definitely things like hover effects, basic animations, often pure CSS now. The chapter revisits how CSS gets included external link tags, internal style tags, or inline style attributes.
Inline styles being generally less.
Manageable usually yeah, harder to maintain consistency. It also teases creating style tags with JavaScript itself, which comes later.
Event listeners again the bridge between user actions and JavaScript. Mentions event bubbling.
Yeah, the idea that an event like a click starts with the specific element clicked the target and then bubbles up the dom tree to its parent, its parent's parent, and so on up to the document.
And on click and default AD event listener listen during this bubbling phase.
Correct. There's also a capture phase where the event travels down the tree first, but bubbling is more commonly used. You can listen in capture phase with AD event listener type listener.
True okay, and clarifies event dot current target versus event.
Dot target crucial difference. Event dot target is the element where the event originated ug The specific thing clicked event dot current target is the element the listener is actually attached to, which might be a parent element if you're using event delegation. Got it?
How can JavaScript change CSS directly.
Through the element's style property my element dot style dot color. It kills red my element dot style dot margin top equals ten px.
So you access CSS properties as JavaScript object properties. What about properties with hyphens like background color.
You can't use dot notation because the hyphen isn't valid and JavaScript identifies there.
Yeah.
Two ways, either use CamelCase my element dot style dot background color equals blue, or bracket notation my element dot style background color equals blue.
CamelCase seems common, but the more recommended way is often using classes right via dot class list.
Generally, yes, it keeps your styling rules neatly in your CSS files. Script just toggles classes on and.
Off like the example. Add a listener to an H one on click event dot target dot class.
List dot toggle different color.
And you'd have a CSS rule like H one dot differentcolor, dot blue or whatever. Much cleaner separation of concerns.
Can you remove listeners to remove event listener?
Yes, but you need to pass the exact same function reference that you used with ad event listener.
So if you use anonymous function like element dot ad event listener, you can't easily remove it. Not easily, you usually need to define the listener as a separate named function. First function handle click element dot ad event listener look at a handleclick, Then you can do element dot remove event listener clickcandleclick okay.
CSS transitions for smooth changes.
Yeah. Instead of style snapping instantly, they animate over time. You define the transition in CSS which property how long it takes duration, maybe a timing function like ease in out.
Then JavaScript just changes the property value.
Yep. If you have transition background color point five's ease on an element and JavaScript changes element dot style dot background color, the browser animates the color change over half a second.
Can you set the transition itself?
With JavaScript?
You can set element dot style dot transition of course opacity ones linear and then change element dot style dot opacity.
What if you change a property multiple times quickly before a transition finishes, it.
Can get complicated the browser might skip intermediate steps. The book introduces the transition.
Event with fires when when a.
CSS transition completes, you can listen for it element dot ad event list function to run code after the animation is done.
Useful for chaining animations or cleaning up. Finally, creating CSS rules dynamically advanced stuff.
You can create a style element in JavaScript let style l document dot, create element style, depend it to the head yep document dot head dot a pin child style call. Then you can access its sheet property style l dot sheet and use methods like insert rule dot dynamic class coolor dot green to add CSS rules as strings.
Wow. Okay, so programmatic control over styles.
Powerful, but use with care. Usually managing classes is simpler.
Chapter eight focuses on showing and hiding content. Uses an example page showing hiding dot HTML.
Right with sections initially hidden by CSS.
How do CSS hide things the display.
Proper displayed none. It's the common way. It completely removes the element from.
The layout, and to show it again, display dot block for block elements or display dot inline exactly.
The example uses CSS rules like hide the div right after an H two, but if the H two also has the class open, then show the following div using display dot block.
So JavaScript's job is just to toggle that open class on the H two when it's.
Click precisely get all the h twos with query selectoral, add a click listener to each inside the listener dot event, dot target, dot class list dot toggle open, Simple and effective.
The chapter then detours briefly into variable hoisting.
Again just a.
Reminder, var declarations and function declarations are hoisted conceptually moved up, let and com okay.
Then a more complex example highlighting nested lists inside an open section.
Yeah, if you click an H two to open its div, maybe you also want any o inside the parent lie of that div. To get a highlight class.
Requires navigating the dom tree using parent note to go up, then query selector to find the full yep.
Bit a dom traversal. Then toggle the highlight class on the nested doll.
And it addresses fixing the logic so highlighting is removed correctly when the section is closed.
Right, making sure the state is managed properly on toggle.
Then it suggests putting this toggle logic into a reusable toggless function in library dot JS.
Good practice abstracting common patterns.
The chapter finishes by enhancing radio buttons, making them de selectable.
Yeah, normally you can only switch radio buttons, not turn the current one off.
How do you make it de selectable.
Get all the radio buttons in the group agmform dot elements group name, add a click listener to each one.
Inside the listener, check of.
The button you just clicked event dot target was already checked before the click event fully processed. This is slightly tricky. Might need to store previous date briefly or check within the listener carefully if it was already checked. Set its jecked property to false.
Ah okay allows toggling off, and this logic also gets moved to a reusable de selectable radio function in the library YEP.
The chapter summary mentions using CSS display, but also maybe max height or opacity for transitions and JavaScript class toggling for show heid effects cool.
Chapter nine another big project a light box gallery wreck.
A thumbnail see a larger version in an overlay.
Basic htmail gallery of thumbnail images, probably wrapped in anchor a tags. The A graph of the anchor points to the large image URL and.
Maybe some CSS to style the thumbnails like desaturate them.
Initially, the JavaScript starts with a dawn light box function. First step find all those thumbnail anchor tags using query selectorol YEP.
Then dynamically create the light box elements in Java.
Script a background div hashtag, light box background to dim the page.
Right and a container. Maybe have a figure eyed light box to hold a big MG, and maybe.
A caption u CSS to style these fixed position centered semi transparent background exactly.
Then appen these new elements to the document body.
How does clicking a thumbnail trigger it?
Attach a click listener to each thumbnail anger inside the.
Listener first event dot, prevent default to stop the link navigating crucial.
Then get the ape ref from the clicked anchor, which is the URL of the large image.
Set the ASRC of the light box's MG element.
To that r right.
Maybe set the alt attribute to Then make the lightbox visible by setting the display style of the background and the container to block.
How do you close it?
Add a click listener to the background div when clicked, set the display of the background and container back to none.
Keyboard navigation, escape key to clothes, arrow keys to go next, previous listen for.
Key up on the document, use event dot key.
In a switch statement case escape dot hide, light box, break case arrow left, show previous image, break.
Like that exactly. Home key for first image and key for last How does.
Show previous image. Work needs refactoring.
Yeah, The book suggests storing a reference to the currently shown thumbnails anchor tag. Let's call it current anchor okay, and create a separate load image anchor to show function. This function takes an anchor element, gets its ATRAF, sets the light box image src, maybe updates.
A caption so the errorkey listeners just figure out the next or previous anchor element in the dom.
Using things like current anchor dot parent, noode dot, previous elements sibling, or next element sibling to find the sibling a's parent, say maybe, then the next prey sibling then it's child A.
And then call load image with that new anchor element.
Precisely need to handle wrapping around at the start ten of the gallery. Two.
What about ensuring the image is loaded before showing mg dot.
Onload Yes inside load image before setting the light box displayed a block, You could set the mmg dot src that attach an onload listener to the image inside the onload handler. You then make the light box visible prevents showing an empty box.
Adding fade effects CSS transitions on opacity.
Yeah, add a CSS transition rule for opacity to the light box container. Or image.
Then in JavaScript, when showing, after setting the iss and maybe inside the onload, add a class like open that sets opacity one.
Right, and when hiding, maybe add a closed class that sets opacity zero. Wait for the transition using transition door, set time out, and then set display none.
Nice. The chapter also revisits the slide show to add a cross fade.
Briefly, yeah, more complex. Setup two mm and tags one on top of the other. Hashtag cross fade absolutely positioned inside a relative container.
CSS transition on the opacity of the top image.
Hashtag crossfait right, triggered.
By a class, say fading, which sets opacity the JavaScript logic, copy the current images src to hashtag crossfade, make sure hashtag cry sat opacity is one, then add the fading class to start the fade out of the top image.
Okay, revealing the main image underneath.
Well almost. After adding fading, you wait for the transition duration for example using set time out. Then you update the main underlying mag tag with the next slide's src, and finally reset the hashtag cross fade image, Remove fading, maybe copy the new main image src to it ready for the next fade. It's a bit fiddly, might need to force a reflow sometimes too.
Sounds complex but creates a nice effect.
Okay.
Last chapter covered Chapter ten introduction to.
AJX, a syncretist JavaScript and XML. They're now mostly Jason.
The key idea fetching data from a server without a full page reload.
Exactly makes web apps feel much more responsive like desktop applications, think dynamic updates, loading content on demand. The previous projects already did a simple version by fetching images.
It mentions the shift from the old XML HTTP request object.
To the modern fetch API, using the fetch function much cleaner syntax.
The big challenge is handling the asynchronous part. JavaScript doesn't wait.
Right fetch and JavaScript immediately moves on to the next line. The server response arrives later.
How do you handle that delayed response?
Promises Yes, fetch returns a promise object. A promise represents the eventual result of an asynchronous.
Operation, and you use dot then to say what should happen when the promise resolves, I e. In the server response.
Exactly fetch my data dot Jason that handle response. Handle response. The function inside only runs after the response arrives, and.
The response object isn't the data itself, yet no, it.
Represents the HTTP response. You need to call methods on it to extract the body data like response dot text or response.
Dot json, and those methods also return promises because reading the body can also take time.
Correct so you often chain dot then calls dot fetch data dot json, dot evil, then data out out data holds the part Jason objectory.
Okay, that structure makes sense, and Jason is the common data.
Format very common JavaScript object notation, human readable text format that looks just like JavaScript objects in arrays, easy for JavaScript to parse, easy for servers to generate.
The chapter shows fetching a slides dot json file an array of image objects.
YEP src, MMG one dot jpg caption. First netch uses fetch and json to get this array into a JavaScript variable, and then.
Uses this data to dynamically build the light box gallery exactly.
Instead of having the HTML hard coded, it loops through the fetched deray. For each object, it creates the A and MG elements using maybe insert adjason HTML.
Puts them into a containertiv hashtag catalog.
And then calls the do light box hashtag catalog function we discussed earlier to make the newly created thumbnails.
Interactive, so the gallery content comes from the server on demand. Cool. Final example populating a form with fetch data.
Yeah, an HTML form with outputs and a select drop down.
Step one fetch a list of countries, maybe IDs, and names from the server as JSON.
Right loops through the fetched de array and dynamically create option elements, adding them to the select dropdown.
Step two add an event listener to the select element. When the user chooses a country.
The listener triggers another fetch request, this time asking the server for detailed data about the selected country using its ID.
Step three. When that detailed data arrives, another promise resolution.
The JavaScript updates the output fields in the form output, span, etc. With its specific details continent, currency, whatever.
So the form populates dynamically based on user selection, fetching only the data needed.
Exactly, a very common pattern in modern web applications.
Wow okay, So wrapping this up, we've really gone from the absolute basics variables syntax.
Through manipulating the page with the DOM, handling user.
Events, interacting with CSS for styling and transitions.
All the way to asynchronously fetching data from a server using ajax and fetch. It's quite a journey.
It really lays the groundwork for understanding how modern interactive websites are built. JavaScript is just everywhere under the hood.
It's incredibly powerful and versatile. This teep dive gives you, hopefully a really solid conceptual map.
Absolutely and if you want to go deeper, definitely experiment play with the code. The book mentions resources like MDM, webdocs and stack.
Overflow indispensable resources for any web developer.
Cannot recommend them enough for sure, So as we finish, here's something to think about. This ability for a webpage to change itself dynamically, to talk to servers without reloading it fundamentally changed the Internet, didn't it completely.
It's the foundation of web applications as we know them.
So consider how this power continues to evolve. What new kinds of interactions, what new online experiences might this dynamic capability make possible in the future.
