The Document-Object Model is the 'glue' that connects Javascript to the data on web pages.
So far we've been working with the "element heirarchy", a set of interconnected objects that represent the text and HTML tags on a web page. When we change a property of one of these objects, the web page is updated to match.
var theParagraph = document.getElementById('para1');
theParagraph.style.background = '#333';
theParagraph.style.color = '#eee';
theParagraph.style.padding = '10px';
By itself this is boring and actually bad code! We should just write this directly into our HTML/CSS instead of using JavaScript, right?
What if we change stuff on the page when the person viewing the web page does something interesting?
Events are another part of the DOM that we haven't talked about yet. They let Javascript programs respond to user interactions such as clicks, mouse movements, etc. Test Link
var clickCallback = function() {
log('The link was clicked.');
};
var linkEl = document.getElementById('testLink');
linkEl.addEventListener('click', clickCallback);
All we have to do is create a function that we want to run, and then attach it
to the DOM using the addEventListener
method that's bulit-in to DOM element
objects.
Note: In IE versions 8 and below, you have to use the attachEvent
function
instead of addEventListener
. Don't worry about that for now, because we're
going to learn jQuery soon, and it handles this detail behind the scenes.
One more detail: JavaScript provides your event handler with an object of
information about the event that happened. More on this later,
but for right now you need to know one thing: event.preventDefault()
var handler = function(event) {
log('Get off of Facebook')
log('and pay attention!');
// Stop the browser from following the link.
event.preventDefault();
};
var linkEl = document.getElementById('testLink2');
linkEl.addEventListener('click', handler);
The "default action" is different depending on the element you're listening to:
DOM Events | 1 |
---|---|
Review: The DOM | 2 |
DOM Events | 3 |
Available Events | 4 |
DOM Events | 5 |
Table of Contents | t |
---|---|
Exposé | ESC |
Presenter View | p |
Source Files | s |
Slide Numbers | n |
Notes | 2 |
Help | h |