John John - 6 months ago 9
Javascript Question

Function gets called many times

I use jquery to

mouseenter
and
mouseleave
, the problem is when I pass from one div to another div, it run again, so I just need to run one time one mouse enter and mouse leav.

<div class="row">
<div class="col-md-4 header" ><img src="http://www.mandroid.in/demo/srems/images/news_image_01.jpg" /></div>
<div class="col-md-4 header" ><img src="http://www.mandroid.in/demo/srems/images/news_image_01.jpg" /></div>
<div class="col-md-4 header" ><img src="http://www.mandroid.in/demo/srems/images/news_image_01.jpg" /></div>
<div class="col-md-4 header" ><img src="http://www.mandroid.in/demo/srems/images/news_image_01.jpg" /></div>
</div>


body {
height:1000px;
width:100%;
background-color:#F0F0F0;
}

#header_div {
width:100%;
height:100px;
position:fixed;
top:0;
left:0;
}
#header_div img {
max-height: 100%;
max-width: 100%;
}

$(document).ready(function () {
$(".header").mouseleave(function () {
$(".header").animate({
height: "50px"
}, 600);
});

$(".header").mouseenter(function () {
$(".header").animate({
height: "100px"
}, 600);
});
})


There is a Jsfiddle of my problem:
https://jsfiddle.net/DTcHh/21266/

Answer

Add a master-header class at the parent div.

 <div class="row master-header">
    <div class="col-md-4 header" ><img src="http://www.mandroid.in/demo/srems/images/news_image_01.jpg" /></div>
    <div class="col-md-4 header" ><img src="http://www.mandroid.in/demo/srems/images/news_image_01.jpg" /></div>
    <div class="col-md-4 header" ><img src="http://www.mandroid.in/demo/srems/images/news_image_01.jpg" /></div>
    <div class="col-md-4 header" ><img src="http://www.mandroid.in/demo/srems/images/news_image_01.jpg" /></div>
</div>

Then do the event on that:

$(document).ready(function () {
   $(".master-header").mouseleave(function () {
       $(".header").animate({
           height: "50px"
       }, 600);
   });

   $(".master-header").mouseenter(function () {
       $(".header").animate({
           height: "100px"
       }, 600);
   });
})

Add a height (and maybe width too):

.master-header {
  height: 400px;
}

Also, consider detaching the mouseenter event if it's already animating Reattach once it's done animating.

Comments