Question

Okay, so essentially, I have, say, 3 links, some text, then 3 divs. (eg:

<a href="#A">A</a><br/>
<a href="#B">B</a><br/>
<a href="#C">C</a><br/>
<p>Blah blah</p>
<div id="A">BlAh</div>
<div id="B">BlBh</div>
<div id="C">POMEGRANTE!</div>

Now, at the moment, you click A and jump to A, etc. and it highlights the div that it selects because of CSS's :target selector. But, I would also like to highlight link A (in a different way to the div) while having div A selected. Are there any ways in Javascript or CSS to do this that don't require weird and/or unstable workarounds?

Was it helpful?

Solution

You could give an "active" class to the link upon click. Here's an implementation using jQuery

$('a').click(function(){
    $('.active').removeClass('active');
    $(this).addClass('active');
});

Demo fiddle

And a native Javascript one:

var elems =document.getElementsByTagName("a");
for (var i = 0; i < elems.length; i++) {
        elems[i].addEventListener("click", function (e) {
                for (var i = 0; i < elems.length; i++) {
                    elems[i].className="";
                };
                this.className = "active";
        });
}

OTHER TIPS

I think you can do like this also..

$('div').click(function(){
    $('a').css('color','');
 $('a[href=#'+$(this).attr("id")+']').css('color','red');
})

Here you go:http://jsfiddle.net/f4FF4/6/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top