tags:

views:

21

answers:

1
+1  Q: 

jQuery check link

1) We have a page index.html with blocks:

<body>
<div id="action1">One</div>
<div id="action2">Two</div>
<div id="action3">Three</div>
</body>

2) CSS

body div { color: blue; }
body div.current { font-weight: bold; color: red; }

3) Other pages with links to index.html and some target:

<a href="index.html#action1">Link to One</a><br/>
<a href="index.html#action2">Link to Two</a><br/>
<a href="index.html#action3">Link to Three</a><br/>

The question is how to catch current link target on page index.html and give extra class for target block.

If current link of opened page is index.html#action1, then add class .current to <div id="action1">One</div>- will become <div id="action1" class="current">One</div>

If index.html#action2-> <div id="action2" class="current">Two</div>

And so on.

  • check #target
  • check id
  • if target = id addClass("current") for block with id

Thanks.

+3  A: 

You can do this:

$(function() {
  if(location.hash) $(location.hash).addClass("current");
});

This uses the location's hash property (if there is one), it'd be "#action1" as an ID selector then adds the class via .addClass(), short and simple :)

Nick Craver
hot to remove "#" from value?
Happy
@Happy - You wouldn't want to if you're using it as a selector, you *want* that `#` prefix. If you need the value for something else, just call `location.hash.replace('#','')`
Nick Craver
sorry, this works perfectly. Thanks :)
Happy