I’ve recently discovered a website which does something really cool! Example:
- There are two links “Cat” and “Dog”.
- There are two DIV containers, id=”catImage” and id=”dogImage”
- The initial URL looks like http://mysite.com/#cat
- Initially, the cat image is visible
- Clicking on the Dog link will fade out the
catImagediv and fade in thedogImagediv - Additionally, it will change the anchor in the browser URL to: http://mysite.com/#dog
- Opening the website with httü://mysite.com/#dog will show the dog image initially
Is this possible using jQuery? How would I scan for that anchor, and how would I call a function when the link is clicked without causing the link to follow some URL? I’m an objective-c dude and don’t know anything about JS… hope my question isn’t too dumb for you.
with this markup:
and with this js (assuming jquery 1.4.x)
And to explain what’s going on here:
I’m using the jquery index() function to get the index of the element relative to its siblings. I then pass that index to the fadeImage function, which finds the same index div and fades it in. By using chaining, I then look to the siblings of that div to fade them out. This is useful if you have more than 2 divs to fade out here.
For the anchor/hash usage, I just find the div with the matching id and get its index, and pass it to the same function.
jQuery docs can explain the various methods much better than I can.