HTML and CSS Reference
In-Depth Information
}
};
}(DOMParser));
</script>
The code in Listing 4-4 might look slightly confusing and long-winded, but it will
allow you to load external HTML documents and traverse its DOM like a regular
HTML document and pick out elements from it. It also binds any links with the
data-method attribute set to xhr .
The benefit to doing it this way, compared to using XML or JSON, is that if you
want to degrade the web application to work on devices without JavaScript
support, you don't have to do as----
-you do not need to make a different view,
you can simply remove the JavaScript code to move between pages.
To do this, the first thing we do is set up the page as shown in the following
snippet.
<div id="container">
<div id="card">
<h1>Page 1</h1>
<a href="index2.html" data-method="xhr">Page 2</a>
</div>
</div>
This creates a container to house the cards. Within the container, there is a
basic card with a header and link. HTML5 allows us to set custom attributes in
the markup using data attributes.
Next, you must bind all of the links to a JavaScript method using the following
code snippet.
function bindLinks(){
[].forEach.call(document.querySelectorAll("#container a[data-method]"),
function(el){
if(el.getAttribute("data-method") == "xhr"){
el.addEventListener("click", function requestCard(event){
loadCard(this.href);
event.preventDefault();
});
}
});
}
This functionality is contained within a function called bindLinks so that it can
be used a little latter. The second line in this method iterates through the list of
 
Search WWH ::




Custom Search