Reputation: 992
Im trying to fix my mouseout event.
Ive got the element
<div id="dropdown"></div>
to show when Im hovering on it. But I want it to dissapear when theres a mouseout event on the ".page_item.page-item-2" element AND #dropdown element.
Here's my Jquery code (that dosen't fully work)
$(document).ready(function(){
$("#dropdown").css('display', 'none');
$(".page_item.page-item-2").hover(
function() {
$("#dropdown").fadeTo("fast", 1.0);
});
var s = $(".page_item.page-item-2").mouseout;
var b = $("#dropdown").mouseout;
if(s && b){
$("#dropdown").fadeTo("fast", 0.0);
}
});
Im sure theres a simple solution to this. Please help
Upvotes: 0
Views: 1285
Reputation: 6256
You could set a timeout in the mouseout event to fade out the element after some time. And reset the timeout everytime a mouseenter event occurs. Here is a full working minimal example.
<div class="page_item page-item-2">Hello</div>
<div id="dropdown">World</div>
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#dropdown").css('display', 'none');
function clear_timeout() {
clearTimeout($("#dropdown").data('timeout'));
$("#dropdown").fadeIn("fast");
}
function set_timeout() {
var timeout = setTimeout(function(){
$("#dropdown").fadeOut("fast");
$("#dropdown").css('display', 'none');
}, 100);
$("#dropdown").data('timeout', timeout);
}
$(".page_item.page-item-2").mouseenter(clear_timeout);
$("#dropdown").mouseenter(clear_timeout);
$(".page_item.page-item-2").mouseout(set_timeout);
$("#dropdown").mouseout(set_timeout);
});
</script>
Upvotes: 1
Reputation: 1690
Why would this not work?
$(document).ready(function(){
$("#dropdown").css('display', 'none');
$(".page_item.page-item-2").mouseenter(function() {
$("#dropdown").fadeTo("fast", 1.0);
});
$(".page_item.page-item-2").mouseout(function() {
$("#dropdown").fadeTo("fast", 0.0);
});
$("#dropdown").mouseout(function() {
$("#dropdown").fadeTo("fast", 0.0);
});
});
EDIT: Because the specification has changed(story of our lives?), here's a rework of my solution. If the relationship between the two elements is simple, like parent-child, this would be super easy...But if they are distant cousins, the below code should still work. I don't like it much...but I think it should work.
var mouseEnterCounter= 0; //allows FadeOuts when equal to zero
$(document).ready(function(){
$("#dropdown").css('display', 'none');
$(".page_item.page-item-2").mouseenter(function() {
mouseEnterCounter++;
$("#dropdown").fadeTo("fast", 1.0);
});
$("#dropdown").mouseenter(function() {
mouseEnterCounter++;
});
$(".page_item.page-item-2").mouseout(function() {
mouseEnterCounter--;
if(mouseEnterCounter == 0)
$("#dropdown").fadeTo("fast", 0.0);
});
$("#dropdown").mouseout(function() {
mouseEnterCounter--;
if(mouseEnterCounter == 0)
$("#dropdown").fadeTo("fast", 0.0);
});
});
Upvotes: 3