jquery - how to avoid mouse event conflict with timer -
my goal hover element on webpage, in case li tag, causing main image swap alternate one. while mouse hovers li tag, alternate image visible. alternate image remain visible n seconds after mouse has left li tag. initial hover action not triggered again until alternate image has swapped main image after n seconds.
my search far has lead me to: detect if hovering on element jquery. forked jsfiddle meligy , came this:
var $sample = $("#sample"); var $main = $("#main"); var $alt = $("#alt"); $alt.hide(); setinterval(function () { if ($sample.is(":hover")) { $main.hide(); $alt.show(); } else { setinterval(function(){ $alt.hide(); $main.show(); },3000); } }, 200);
also, jquery on hover animation fires multiple times , using fc's jsfiddle came happens surprisingly close.
var $hover = $("#hover"); var $main = $("#main"); var $alt = $("#alt"); $alt.hide(); $hover.hover( function () { $alt.stop(true, true).show(); $main.stop(true, true).hide(); }, function () { $main.stop(true, true).show(2000); $alt.stop(true, true).hide(2000); });
so far nearest thing have below after few hovers images flutter , forth uncontrollably.
var $hover = $("#hover"); var $main = $("#main"); var $alt = $("#alt"); $alt.hide(); $hover.hover(function () { if ($main.is(":visible")) { $main.hide(); $alt.show(); } }, function () { setinterval(function () { // attempted $main.is(":hidden") if ($main.not(":visible")){ $alt.hide(); $main.show(); } }, 3000); });
thanks everyone.
use timeout avoid behavior. cause is, interval (timeout too) fire, regardless of hover. have cancel running timeout/interval if leave/reenter element. made edits on code testing purposes:
var timer = null; $hover.on('mouseenter', function () { if (window.timer != null) cleartimeout(window.timer); $main.hide(); $alt.show(); }); $hover.on('mouseout', function () { window.timer = settimeout(function () { // attempted $main.is(":hidden") $alt.hide(); $main.show(); }, 3000); });
the updated fiddle: https://jsfiddle.net/m18volel/5/
Comments
Post a Comment