Highlighting a specific DIV via URL

Hi there, I was hoping that someone here might be able to let me know how to do something that’s probably very simple.

I’ve got a list of DIVs on a page, each one with it’s own unique id, i.e.

<div id="event1">
...
</div>
<div id="event2">
...
</div>
<div id="event3">
...
</div>

Now I’m already able to use the URL to scroll the page down to a specific element on that page via the use of a URL such as www.example.com/page/#event2

This is OK, but what I really want is the ability to take the parameter specified in the URL (the #event2), and use it to somehow highlight that specific DIV.

I figure the easiest way of doing this is to modify the DIV and add a class to it, such as class=“highlight”, then use CSS to set a different background colour - but I know very little about JavaScript, so I don’t know how I would go about doing this.

I’m currently using a little jQuery on the site, so I thought that this might be the best way of achieving this, but I don’t know how.

Can anyone help? Thank you.

You can use location.hash to find out the fragment identifier that was used.

var hash = location.hash; // ‘#event2

You can then slice of the first character to get the name of the identifier.

var id = hash.slice(1); // ‘event2’

And then use that to add a class name. I wouldn’t use highlight though.

document.getElementById(id).className = ‘selected’;

Try using instead a name that explains its purpose, such as “selected”. With highlight, it’s likely to be trapped in a re-design where the class called highlight makes it bold with a border instead, and then the class name becomes useless, or you have to go through all of your code renaming it.

CSS is supposed to help prevent you from the renaming hassle, so by using names that describe the purpose (deck, byline, caption, etc…) you can help to protect yourself from future problems.