HTML and CSS Reference
In-Depth Information
OK, edit the loadFile() function so that it retrieves the message ID from the
hashtag in the URL:
function loadFile() {
// retrieve the hashtag from the URL using the
location object
var messageHash = window.location.hash;
if (messageHash == "") messageHash = "#mes-
sage1";
var file = messageHash.substr(1)+".txt";
//
strip out the "#" from the hashtag
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = responseReady;
xmlhttp.open("GET",file,false);
xmlhttp.send();
}
Now test the page and use the next and previous buttons. You should see the web page
address URL update with the hashtag. This means the individual Ajax-enabled pages of
content can be bookmarked, which is great! However, if you click the browser's forward
or back button, you will notice the message on the page does not update, even though
the URL in the address bar does. The reason for this is that the onload event does not
fire again when the user clicks the forward and back buttons. This is because the page
has been cached by the browser so that it will load faster as the user navigates through
the history. What we need to add is an event that fires when the history has changed, and
thankfully there is such an event called onpopstate . At the very end of the script, add
the following:
window.onpopstate = init;
This will run the init() function every time the history is navigated. This isn't the
most efficient code, because there will be redundant calls to the init() function (for
example, twice when first loading the page), but use this simple example to develop
from.
Search WWH ::




Custom Search