Making webpages interactive with events
About this video
This video explains why changing the DOM with JavaScript matters: you can do it in response to user events. It gives examples like slideshows, games, form validation and infinitely-loading galleries, then describes event-driven programming: the user acts, the browser fires an event, and it calls the listener function your code set up.
You'll be able to
- explain why modifying the DOM is more useful when it happens in response to user events.
- match common interactive features to the user events they respond to.
- describe the steps of event-driven programming: user action, event fired, listener function called.
Key words
- DOM
- The browser's model of your webpage that JavaScript can access and change.
- event
- Something that happens in the page, like a click, key press, typing or scrolling, that the browser announces.
- fire (trigger)
- When the browser announces that an event has happened on an element.
- listener function
- A JavaScript function you set up ahead of time that the browser calls when a particular event happens.
Transcript
Now you all know how to access and modify the DOM of your webpages. And you can do that for hours on end. But why would you do that when you could just start the webpage off with the HTML that you wanted? Because now you can do all of that in response to user events.
And that is what makes JavaScript on webpages so powerful. For example, you could create interactive slideshows by responding when the user clicks a button. You could create games of all sorts, responding when the user presses keys or moves their mouse to aim a bird.
You can process forms and validate user input, responding when the user types in the form. You could create infinitely-loading galleries, responding whenever the user scrolls the page. All of that is possible by listening to events in your webpage. The user will do some action, like click a button.
The browser then fires-- or triggers-- the click event on that button, and your code already has a listener function set up for that event, so the browser then calls your listener function, which is some bit of JavaScript that you want to happen in response. That's the basic gist of how it works, and now I'm going to show you how to actually code it in your webpage.
Video © Khan Academy, used under CC BY-NC-SA. Watch on Khan Academy. Puzzicle is not affiliated with Khan Academy.