Reputation: 684
How to change global var value on div hover.
When I hover on Class .mehover
or .mehoverAnother
the class 'hideplease' will be added to .mehide
or .mehideAnother
. When on hoverOut remove the class .mehide
or .mehideAnother
but delay the removal of a class by 2s and if each time I hover on .mehover
or .mehoverAnother
change the timetolive variable value to 0.
see my code below:
Javascript
var timetolive = 2000;
$(document).ready(function() {
$('.meHover').hover(function() {
//code here to change the timetolive var value
//the .mehide or .mehideAnother should hide immediately by changing the timetolive var value to 0
$('.mehide').addClass('hideplease');
}, function() {
setTimeout(function(){ $('.mehide').removeClass('hideplease'); }, timetolive); //delay removal of class
});
$('.meHoverAnother').hover(function() {
//code here to change the timetolive var value
//the .mehide or .mehideAnother should hide immediately by changing the timetolive var value to 0
$('.mehideAnother').addClass('hideplease');
}, function() {
setTimeout(function(){ $('.mehideAnother').removeClass('hideplease'); }, timetolive); //delay removal of class
});
});
HTML
<div class="container">
<div class="meHover">hoverme</div>
<div class="meHoverAnother">other hoverme</div>
<div class="mehide"></div>
<div class="mehideAnother"></div>
</div>
jsfiddle sample here https://jsfiddle.net/pqn01e5h/9/
Upvotes: 0
Views: 723
Reputation: 2766
Try the below code.
var timetolive = 2000;
$(document).ready(function() {
$('.meHover').hover(function() {
timetolive = 0;
$('.mehide').addClass('hideplease');
}, function() {
timetolive = 2000;
setTimeout(function(){ $('.mehide').removeClass('hideplease'); }, timetolive); //delay removal of class
});
$('.meHoverAnother').hover(function() {
timetolive = 0;
$('.mehideAnother').addClass('hideplease');
}, function() {
timetolive = 2000;
setTimeout(function(){ $('.mehideAnother').removeClass('hideplease'); }, timetolive); //delay removal of class
});
});
.container {
width: 100%;
height: 100%;
color: white;
}
.meHover {
width: 120px;
height: 40px;
background: red;
margin: 20px 0 0 0;
position: absolute;
}
.meHoverAnother {
width: 120px;
height: 40px;
background: blue;
margin: 20px 0 0 120px;
position: absolute;
}
.mehide {
width: 120px;
height: 40px;
background: yellow;
position: absolute;
margin: 60px 0 0 0;
}
.mehideAnother {
width: 120px;
height: 40px;
background: orange;
position: absolute;
position: absolute;
margin: 60px 0 0 120px;
}
.hideplease {
display: none;
opacity: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="meHover">hoverme</div>
<div class="meHoverAnother">other hoverme</div>
<div class="mehide"></div>
<div class="mehideAnother"></div>
</div>
Upvotes: 1