I have list item
.thumbs {display: flex;}
.thumbs .item {width: 150px; height: 150px; margin-right: 10px; border: 1px solid black}
.thumbs .item.active {border: 1px solid red}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="thumbs">
<div class="item active">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
</div>
How to hover .thumbs .item
add active to item:hover
& clear active item(1).
And if not hover any item stick active item last hover.
same as:
hover item(2)
: add active item(2)
- Clear active item(1)
&& If don't hover any item or hover out .thumbs
element stick active item(2).
I user js hover active but not hover clear all active.
$(document).ready(function() {
$(".thumbs .item").hover(
function() {
$(this).addClass('active');
}, function() {
$( this ).removeClass('active');
}
);
});
Don't forgot before add active
class remove all the class and then add it to current element:
$(".item").removeClass('active');
$(this).addClass('active');
And for last item use mouseout
event for .thumbs
. You need to keep last Element
when an element unhovered (lastElemtHoverd = $(this);
)
$(document).ready(function () {
var lastElemtHoverd;
$(".thumbs").mouseout(function () {
lastElemtHoverd.addClass('active');
});
$(".thumbs .item").hover(
function () {
$(".item").removeClass('active');
$(this).addClass('active');
}, function () {
$(this).removeClass('active');
lastElemtHoverd = $(this);
}
);
});
.thumbs {
display: flex;
}
.thumbs .item {
width: 150px;
height: 150px;
margin-right: 10px;
border: 1px solid black
}
.thumbs .item.active {
border: 1px solid red
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="thumbs">
<div class="item active">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
</div>