Buzz
Buzz

Reputation: 1619

How to apply a class on <li> when mouse is hovering on it?

I defined a CSS class "active", and want to apply this class on a <li> tag only when the mouse is hovering on it. How to do that?

Here is a Bootstrap example:

<ul class="list-group">
  <li class="list-group-item">First item</li>
  <li class="list-group-item">Second item</li>
  <li class="list-group-item">Third item</li>
</ul>

And when the mouse is hovering on any <li>, apply class "active" on it.

Hope CSS could provide something like this, because I want to avoid writing same plain CSS text again and again.

.list-group-item:hover
{
    include .active;
}

Thanks.

Upvotes: 0

Views: 2099

Answers (5)

katecao
katecao

Reputation: 1

hover on every li

li:hover{
  background-color: #ffeeff;
}

hover on class list-group-item

.list-group-item:hover{
  background-color: #ffeeff;
}

hover on li with class list-group-item

li.list-group-item:hover{
  background-color: #ffeeff;
}

Upvotes: 0

Nocturnal Penguin
Nocturnal Penguin

Reputation: 153

you should avoid using unnecessary javascript when you can do it simply with CSS, like everyone else pointed out already

but nonetheless jquery way would be

$('.list-group-item').hover(function(){
    $(this).addClass('active');
},function(){
    $(this).removeClass('active');
});

first block is when the mouse is over the element, second is when it leaves it https://jsfiddle.net/o9na7ps0/1/

Upvotes: 1

marc_s
marc_s

Reputation: 455

Why do you want to create a class .active?
you should do it this way:

.list-group-item:hover {
   /* body of the active class here*/
}

this way, you don't need to create a seperate class for the hovering.

Upvotes: 1

Faisal
Faisal

Reputation: 1925

Try This:

HTML <li class="active list-group-item">First item</li>

CSS li.active:hover {...}

Upvotes: 0

Adam Buchanan Smith
Adam Buchanan Smith

Reputation: 9449

Add this .list-group-item:hover{color: white;} to your CSS like this example https://jsfiddle.net/7sud8341/2/

Upvotes: -1

Related Questions