detect and change html named anchor tags in the url through javascript and jquery Oct

You may already be familiar with using html named anchor tags to auto-scroll the page to a certain section in an html page, which would look something like this:

<a id="button" href="#tag">link</a>


<a name="tag">anchor</a>

An alternative use for anchor tags is to change and detect the tag value in the url on the fly in order to initialize certain states with javascript-driven content. This is handy as it lets people bookmark the location and the page will initialize properly even in heavy ajax environments. It's surprisingly easy to interact dynamically with the url anchor tag object.

You can detect the current anchor value of the url in javascript through "location.hash" like this:

if(location.hash == '#tag') {
    // initialize content

You can also dynamically change the anchor tag in the url just by setting "location.hash" like so:

// location.hash = 'value';

$('a#button').click(function(event) {

    // set the anchor value
    // I like to strip the hash out of the href value; you can use your own method of choice to determine the anchor.
    location.hash = $(this).attr('href').replace('#', '');

    // do something important

These examples use JQuery to simplify the code.

Bookmark and Share
blog comments powered by Disqus