HTML and CSS Reference
In-Depth Information
HTML elements or the NodeList returned from the query selector. The method of
doing this looks slightly complicated. You first begin by creating a new empty
array object using
[]
. From here, you use the
call
method to run the
Array
object's
forEach
method within the context of the NodeList returned from the
query. The
forEach
method accepts a callback function as the first parameter.
The callback function also accepts the following three arguments:
The current element being iterated
The current element's index within the array
The actual array
You will only need the current element so that you can use it within your
callback function; this is called
el
.
The third line within this method checks to see whether the attribute
data-
method
exists and that the value is
xhr
. If this is true, it adds an event listener to
the link. This allows you to manually specify which links should be pulled in via
Ajax.
The fourth line adds an event listener to the click event. The click event acts in
much the same way as it does on the desktop, with the exception that if a user
drags his finger away from the link, it will cancel the event. You use a named
function for this so that it can be tracked in a call stack when debugging in
Android Browser or Chrome for Android.
Within the event listener function, when the user taps the link, the method
loadCard
is called with a parameter containing the link's intended path
event.target.getAttribute("href")
. This is taken from the link's
href
attribute.
event.preventDefault();
stops the link from being followed through in the
browser, and the next page from loading in the usual way.
The
loadCard
function shown in the next code snippet will load the html from the
path parameter using an
XMLHttpRequest
, fetch the card within the page, and
replace the card on the current page with the new content using the
setCardContent
method. After that is complete, the method will rebind the links
with the event handlers so that all further pages are loaded in the same way, as
any new links in the new content will not have event handlers attached to them.
function loadCard(path){
var xhr = new XMLHttpRequest();
xhr.open("GET", path, true);
xhr.onreadystatechange = function contentLoaded(){
if (this.readyState === this.DONE) {