Balabky9
Balabky9

Reputation: 23

Giving an active li element a different background

I am trying to work on achieving some-thing like this as shown in the image taken from IP-Board's website. ip image

My code is like the following:-

<ul class="navmenu">
 <li>//1st drop down box</li>
 <li>// 2nd drop down box</li>

Now I want the li items background to change to white when a user clicks on it. I know this can be done via Jquery but I am not very well versed with it. Hope any one of you can help me.

I tried this guide but did not work How can I highlight a selected list item with jquery?

Also please keep in mind that both the li elements contain jquery drop-downbox.

UPDATE I want the Jquery so that if I click it once more the active class should be removed.

Upvotes: 1

Views: 301

Answers (3)

Aown Raza
Aown Raza

Reputation: 2023

$('ul li').on('click', function(){
$(this).addClass('highlight');
});

and in css add class ".highlight"

.highlight { background-color:red; }

Upvotes: 1

Mohsen Safari
Mohsen Safari

Reputation: 6795

you can get active element by :active after selector like this:

DEMO

CSS

li:active{
    background:red;
}

update:

if you want to background stay red you need to use JQuery. first create a class that you want style the active item like this:

.active{
        background:red;
    }

then use this JQuery code:

$("li").click(function(){
    $("li.active").removeClass("active");
    $(this).addClass("active");
});

jsFiddle is here

Upvotes: 2

alexP
alexP

Reputation: 3765

jQuery:

$('ul li').on('click', function(){
  $(this).toggleClass('highlight');
});

CSS:

.highlight{
    background-color: red;
}

DEMO

Upvotes: 0

Related Questions