Dima Vleskov Dima Vleskov - 4 months ago 23
CSS Question

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");
});
});

Answer

$(".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>

Comments