سؤال

So I'm trying to make a dropdown for the cart on my website, http://www.beautracare.com/ , and so far if I mouse over the cart you get a dropdown fade in, but after a while it times out and fades out even if you're still moused over the cart dropdown. I tried creating a setTimeout and clear it when mousing over the dropdown, but it doesn't respond. I also tried playing around with the dropdown hover function in Jquery but it doesn't seem like its even triggering. Please help, thanks. The jQuery code is given below:

jQuery(document).ready(function() {
    var timer;
    //get all link with class panel
    $('a.panel').click(function () {

                //reset and highlight the clicked link
        $('a.panel').removeClass('selected');
        $(this).addClass('selected');

        //grab the current item, to be used in resize function
        current = $(this);

                //scroll it to the destination
        $('#wrapper').scrollTo($(this).attr('href'), 800);      

                //cancel the link default behavior
        return false;
    });

    $('.wsite-nav-cart').hover(
        function() {
            if ($("#wsite-mini-cart").css("display") == 'none'){
                $("#wsite-mini-cart").fadeIn();
                timer = window.setTimeout(function() {$("#wsite-mini-cart").fadeOut(); }, 1500);
            }
        }, function() {
        }
    );

    $("#wsite-mini-cart").hover(
        function() {
             if (timer) {
                window.clearTimeout(timer);
            } 
            $("#wsite-mini-cart").css({'display':'block','opacity':1});
        }, function() {
            timer = window.setTimeout(function() {$("#wsite-mini-cart").fadeOut(); }, 1500);
        }
    );


    $('.wsite-nav-cart').click(function () {
        if ( $(this).attr("id")){
            $("#wsite-mini-cart").fadeOut();
            $(this).removeAttr('id');
        } else {
            $("#wsite-mini-cart").fadeIn();
            $(this).attr('id', 'active');
        }
        //cancel the link default behavior
        return false;
    });
هل كانت مفيدة؟

المحلول

I made a little jsfiddle to show how I would solve this. If you mouseover the button, the cart shows up. If you mouseout the button, the cart hides. But if you move over to the cart, it stays visible, until you move out from it.

Basically, the hideCart is delayed with 500ms. If any bound element receives a mouseover during this time, it cancels the timer.

The code:

var hideTimer;

function showCart() {
    $("#mini-cart").fadeIn(1000);
    if (hideTimer) {
        window.clearTimeout(hideTimer);
        hideTimer = null;
    }
}

function hideCart() {
    hideTimer = window.setTimeout(function () {
        $("#mini-cart").fadeOut(1000);
    }, 500);
}

$("#nav-cart,#mini-cart").hover(showCart, hideCart);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top