Reputation:
I'm creating my custom animation for some divs while hovering. Like this:
$('.d1').on('mouseover', function () {
$('.d2').animate({ 'margin-top': '-100px' }, 500);
});
$('.d1').on('mouseout', function () {
$(this).css('background-color', 'green');
});
.d1, .d2 {
width: 50px;
height: 50px;
background-size: 50px 50px;
}
.d1 {
background-color: red;
margin-top: 50px;
}
.d2 {
background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div class="d1"></div>
<div class="d2"></div>
I'm getting a trouble: I lost the event mouseover
while the box d2
was moving through d1
and the event mouseout
was caught:
I don't want to hit the event mouseout
while moving d2
. Also I want to use the event when the cursor is really out
from d1
.
My question: Can I ignore to run the event mouseout
while moving d2
? Thank you!
Upvotes: 1
Views: 48
Reputation: 2225
Try to use setTimeout function to make sure d2 was moved completely
$('.d1').on('mouseover', function () {
$('.d2').animate({ 'margin-top': '-100px' }, 500);
setTimeout(function () {
$('.d1').on('mouseout', function () { $(this).css('background-color', 'green'); })
}, 500)
});
.d1, .d2 {
width: 50px;
height: 50px;
background-size: 50px 50px;
}
.d1 {
background-color: red;
margin-top: 50px;
}
.d2 {
background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div class="d1"></div>
<div class="d2"></div>
Upvotes: 0
Reputation: 9959
If I'm understanding your question correctly, you could use the CSS declaration pointer-events: none;
to stop d2
from "blocking" the mouseover d1
$('.d1').on('mouseover', function() {
$('.d2').addClass("noEvents").animate({
'margin-top': '-100px'
}, 500, function() {
$('.d2').removeClass("noEvents");
});
});
$('.d1').on('mouseout', function() {
$(this).css('background-color', 'green');
});
.d1,
.d2 {
width: 50px;
height: 50px;
background-size: 50px 50px;
}
.d1 {
background-color: red;
margin-top: 50px;
}
.d2 {
background-color: blue;
}
.noEvents {
pointer-events: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div class="d1"></div>
<div class="d2"></div>
As mentioned in the comments, if there are no events on the d2
element, this could be simplified to just adding the CSS to the .d2
style, with no JS changes.
$('.d1').on('mouseover', function() {
$('.d2').animate({
'margin-top': '-100px'
}, 500);
});
$('.d1').on('mouseout', function() {
$(this).css('background-color', 'green');
});
.d1,
.d2 {
width: 50px;
height: 50px;
background-size: 50px 50px;
}
.d1 {
background-color: red;
margin-top: 50px;
}
.d2 {
background-color: blue;
pointer-events: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div class="d1"></div>
<div class="d2"></div>
Upvotes: 2