0

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 Answers 2

2

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');
    }
});
Sign up to request clarification or add additional context in comments.

1 Comment

I think this would work (mostly anyway), however what if the link is not clicked. What if the document is loaded with /page/#thisid
0

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();
});

3 Comments

Why does #thisid need to be an anchor? And why are you creating invalid attributes? A bit obtrusive!
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 ;)
Trust me JimmyP, the ladies love it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.