views:

1558

answers:

2

I'm trying to get JQuery to highlight an element based on the link ID selector

For Example

<a href="#thisid">Goto Element with ID name</a>

Highlights the element below.

<div id="thisid" class="isNowHighlighted">FooIsCoolButNotBetterThenBar</div>

Iv tried searching for relevant plugins but no joy. Any ideas?

+2  A: 

So you only want to add a class?

jQuery('a[href^=#]').click(function(){
    var id = this.hash.replace('#','');
    $('#' + id).addClass('isNowHighlighted');
});


EDIT:

In answer to your comment; you could do the same when the page loads:

$(document).ready(function(){
    if (window.location.hash) {
        $('#' + window.location.hash.replace('#','')).addClass('isNowHighlighted');
    }
});
J-P
I think this would work (mostly anyway), however what if the link is not clicked. What if the document is loaded with /page/#thisid
A: 

Since #thisId is not an anchor, it's kind of meaningless so I would do it like :

<a data-highlight="thisid" href="#">Goto ..</a>

$('a[data-highlight]').click(function(event){
    $('#' + $(this).data('highlight')).addClass('isNowHighlighted');
    event.preventDefault();
});
Chad Grant
Why does #thisid need to be an anchor? And why are you creating invalid attributes? A bit obtrusive!
J-P
It doesn't need to be an anchor, but it has no meaning. I think that having an explicit attribute is easier to read/understand. I don't see anything obtrusive about it. I will edit for a less "obtrusive" way for you ;)
Chad Grant
Trust me JimmyP, the ladies love it
Chad Grant