dmitriy
dmitriy

Reputation: 488

how to add class to element when you hover but when you leave mouse the class stay

i can't solved the problem when you hover elements it has to add active class to them but when you hover to something else (another section and so on) this class has to remain on the last element which you hovered. The first block have to be active as a default state.

<div class="work-elem">
<div class="work-elem">
<div class="work-elem">
<div class="work-elem">

$(".work-elem:first").addClass("active");
    $(".work-elem").each(function() {
        $(".work-elem").hover(function() {
            $(this).removeClass("active");
            $(this).addClass("active");
        },
        function() {
            $(this).removeClass("active");
        });
    });

Upvotes: 0

Views: 106

Answers (2)

C.Raf.T
C.Raf.T

Reputation: 383

$(".work-elem").mouseover(function() {
  $(".work-elem").removeClass("active");
  $(this).addClass("active");

});
div {
  width: 20px;
}
.active {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="work-elem active">1111</div>
<div class="work-elem">2222</div>
<div class="work-elem">3333</div>
<div class="work-elem">4444</div>

Upvotes: 5

Abdennour TOUMI
Abdennour TOUMI

Reputation: 93541

Use mouseenter & mouseleave instead of hover :

    $(".work-elem:first").addClass("active");
    $(".work-elem").each(function() {
        $(".work-elem").mouseenter(function() {
            $(this).removeClass("active");
            $(this).addClass("active");
        }).mouseleave(function(){
              $(this).removeClass("active");
        });
    });
.active{
   color:green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="work-elem">What about</span>

Upvotes: 0

Related Questions