Search code examples
jqueryhtmlfragment-identifierbrowser-state

How do I use jQuery to create a bookmark-able hash?


I have a single URL I am using as an image gallery. At this URL is a thumbs div (I'm only showing four thumbs for the sake of brevity):

 <div id="thumbs">
 <img src="graphics/thumbs/01.jpg" width="190" height="190" class="thumb objects" id="project01" />
 <img src="graphics/thumbs/08.jpg" width="190" height="190" class="thumb web" id="project08" />
 <img src="graphics/thumbs/14.jpg" width="190" height="190" class="thumb freehand" id="project14"/>
 <img src="graphics/thumbs/04.jpg" width="190" height="190" class="thumb freehand objects" id="project04" /></div>

And an empty div called #content:

<div id="content"></div>

and a hidden div called #preload:

 <div id="preload">
<span id="project01_content"><img src="graphics/010.jpg" /></span>
<span id="project02_content"><img src="graphics/022.jpg" /><img src="graphics/021.jpg" /><img src="graphics/023.jpg" /><img src="graphics/020.jpg" /></span>
<span id="project03_content"><img src="graphics/030.jpg" width="450" height="600" /><img src="graphics/031.jpg" width="450" height="600" /></span>
<span id="project04_content"><img src="graphics/040.jpg" width="775" height="600" /><img src="graphics/041.jpg" width="775" height="600" /></span></div>

My jQuery uses the ID of the clicked thumbnail to clone() the images from the corresponding span and drop them into #content using the html() method. It works great. Now, I'd like to return to mysite.com/#project01 and have #content already filled with Project 01.

How can I give each image a hashed URL that will call up the same jQuery state?


Solution

  • You can just perform a click on that thumb as soon as the page loads and your current code should execute, like this:

    $(function() {
      if(window.location.hash.indexOf('project') > -1)
        $(window.location.hash).click();
    });
    

    This uses the window.location.hash property which would be "#project01" in your example URL...so it's already an #ID selector, we're just checking that it's a hash we care about, then using that selector to fire a .click(). Just make sure this runs after your current click handler for the thumbs is bound.