Reputation: 358
I have this code:
setInterval (function(){
var r_width=$(document).width();
if(r_width>650){
alert(r_width);
$("#game, #gms").hover(function() {
$("#gms").stop(true, true).fadeIn(500);
}, function() {
$("#gms").stop(true, true).delay(10).fadeOut(400);
});
}
}, 1000);
Condition is true:
When document width is bigger than 650 alert is shown and the code .hover is executed.
Condition is false:
However when document width is less than 650 alert isn't shown but the code is executed.
Why when condition is false the code is executed?
Upvotes: 1
Views: 2174
Reputation: 15827
if the condition r_width>650
evaluates true at least one time (that code is executed every one second as you put it in a setInterval
) the hover
listener is attached to the elements with selector #game
and #gms
.
Then every time the hover event is triggered the code of the callback is executed despite of the value of r_width
Upvotes: 0
Reputation: 318182
The code isn't executed, but you've put an event handler inside the interval, and the event handler isn't removed when the function fires again, it stays, and you just keeping adding more event handlers every second.
Add the event handler once, and do the checks inside the event handler
$("#game, #gms").hover(function() {
if ( $(document).width() > 650 )
$("#gms").stop(true, true).fadeIn(500);
}, function() {
if ( $(document).width() > 650 )
$("#gms").stop(true, true).delay(10).fadeOut(400);
});
Upvotes: 2