I am trying to figure out why my on hover function is acting weird. When you hover over a div, another div becomes visible. However, when I move my cursor down to the div that becomes visible, it fades out and fades back in again. This should not happen and should just stay visible until my cursor leaves the main container.
Here is my code.
HTML
<div id="searchWrapper" class="fleft">
<div class="box">Hover here!</div>
<div class="searchLinks" style="display: none;">
<form id="search_mini_form" action="" method="get">
<div class="form-search">
<label for="search">Search:</label>
<input id="search" type="text" name="q" value="" class="input-text" maxlength="128" autocomplete="off">
<button type="submit" title="Search" class="button"><span><span>Search</span></span></button>
<div id="search_autocomplete" class="search-autocomplete" style="display: none;"></div>
<script type="text/javascript">
//<![CDATA[
var searchForm = new Varien.searchForm('search_mini_form', 'search', '');
searchForm.initAutocomplete('http://removed.com/index.php/catalogsearch/ajax/suggest/', 'search_autocomplete');
//]]>
</script>
</div>
</form>
</div>
</div>
jQuery
<script type="text/javascript">
jQuery(function($) {
$("#searchWrapper").hover(
function () {
$(".searchLinks").fadeIn( 500 );
},
function () {
$(".searchLinks").fadeOut( 500 );
}
);
});
</script>
CSS
#searchWrapper {
position:relative;
}
#searchWrapper .searchLinks {
position: absolute;
z-index: 99999;
top: 50px;
background: #e7e7e7;
right: -145px;
display:none;
padding:10px;
}
#searchWrapper .box {
border:solid 1px #555;
padding: 20px 0px;
text-align:center;
}
You can see here how it fades in and then fades out and back in once you hover over it.
You must use the stop()
function.
jQuery(function($) {
$("#searchWrapper").hover(
function () {
$(".searchLinks").stop(true,true).fadeIn( 500 );
},
function () {
$(".searchLinks").stop(true,true).fadeOut( 500 );
}
);
});
Also, reduce the margin of .searchLinks if you don't want to see it fadeOut when the mouse is between it and it's parent. (padding-top instead of top)
Every time you are hovering the element you must stop the currently-running animation on the matched elements.
Use stop()
Try:
jQuery(function($) {
$("#searchWrapper").hover(
function () {
$(".searchLinks").stop().fadeIn( 500 );
},
function () {
$(".searchLinks").stop().fadeOut( 500 );
}
);
});
Use stop()
and you could use in/out hover method handler as it:
jQuery(function ($) {
$("#searchWrapper").hover(
function () {
$(".searchLinks").stop().fadeToggle(500);
});
});
None of the above worked for me but I found a solution that only fires once using .unbind()
:
$("#sidebar").unbind().on('mouseenter', function() {
console.log('mouse entered sidebar');
});
来源:https://stackoverflow.com/questions/26427021/jquery-on-hover-animation-fires-multiple-times