marquesm91 marquesm91 - 29 days ago 11
CSS Question

Maintain my CSS even if I click outside of the item

I am learning CSS and by now I have this :

https://jsfiddle.net/marquesm91/ahwxwyca/

Basically I want to highlight the element I clicked on and stay highlighted when I click outside of the element. When I am switching between elements it only highlight the actual element.

#menu a:hover,
#menu a:focus {
color: #fff;
background-color: #2a6496;
}


By now, my CSS don't help me. Any suggestions?

Answer

CSS can interact with hover, but does not have the capability to interact with clicks in the way you describe. You will need Javascript.

$('#menu').find("a").click(function(){
    $(this).css("background-color","#2a6496");
    $(this).css("color","#fff");
});

Here's a fiddle.

PS, When making fiddles with jQuery, be sure to select jQuery from the JS menu.


Maybe this is closer to what you want:

$('#menu').find("a").focus(function() {
    $('#menu').find("a").each(function() {
        $(this).css("background-color", "initial");
        $(this).css("color", "initial");
    });
    $(this).css("background-color", "#2a6496");
    $(this).css("color", "#fff");
});

https://jsfiddle.net/zq0cpohb/

This only highlights the last element clicked on..

Comments