Pregunta

I have a div that opens when a button is clicked by using $(element).slideDown();

I'm trying to do three things,

  1. If the mouse is over the element it stays open
  2. If the mouse leaves the element it slideUp() after 5 seconds
  3. If the mouse never hovers the element slideUp() after 5 seconds

What I did was to give the div a class of notHovered. On the button click the container slides down and the time starts on the condition ".intro-wrapper" has the class "notHovered". What I then did was remove that class on the hover to cancel out the if statement in the click. This didn't work, I have a feeling it's because the .notHovered class is binded already?

I'm not sure how to fix this, any help would be greatly appreciated.

    <div class=".intro-wrapper notHovered"></div>

    $("btn").click(function() {
        $(".intro-wrapper").slideDown({duration:300,queue:false});    
        if ( $(".intro-wrapper").hasClass("notHovered") ) {
            setTimeout(function() {
                    $(".intro-wrapper").slideUp({duration:300,queue:false});
            },6000);                
        } 
    });


    $( ".intro-wrapper" ).hover(
    function() {
        $(".intro-wrapper").removeClass("notHovered");
    }, function() {
        setTimeout(function() {
            $(".intro-wrapper").slideUp({duration:300,queue:false});
        },6000);
    });
¿Fue útil?

Solución

Return the timeout to a common variable so it can be cleared if the mouse enters the intro-wrapper element, and reattached if the mouse leaves that element again :

var timer;

$(".btn").on('click', function() {
    $(".intro-wrapper").slideDown(300);
    timer = setTimeout(function() {
         $(".intro-wrapper").slideUp(300);
    }, 5000);                
});


$( ".intro-wrapper" ).on({
    mouseenter: function() {
        clearTimeout(timer);
    },
    mouseleave: function() {
        timer = setTimeout(function() {
            $(".intro-wrapper").slideUp(300);
        }, 5000);
    }
});

and note that $('btn') selects an element looking like <btn></btn> which is not valid, and you'd normally not use the period when declaring a class

<div class=".intro-wrapper notH
 //         ^^ woot
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top