Search code examples
javascriptjquerymouseeventonmouseover

How to delay after on("mouseenter") 2 seconds?


Here is my code.

In the 4th line, I want to run this.openList after 2 seconds when mouse entered lastItemsLink.

How can I do that?

lastItemsLink = $(".last-items"),
openLastItemsList = {
    init: function() {
        lastItemsLink.on("mouseenter", this.openList);
        lastItemsLink.on("mouseleave", this.closeList);
    },
    openList: function() {
        lastItemsContainer.stop(false, true).slideDown("fast");
    },
    closeList: function() {
        lastItemsContainer.stop(false, true).fadeOut("fast");
    }
};

Solution

  • You might have to do something like

    lastItemsLink = $(".last-items"),
    openLastItemsList = {
        init: function () {
            lastItemsLink.on("mouseenter", this.openList);
            lastItemsLink.on("mouseleave", this.closeList);
        },
        openList: function () {
            openLastItemsList.timer = setTimeout(function () {
                lastItemsContainer.stop(false, true).slideDown("fast");
                delete openLastItemsList.timer;
            }, 2000)
        },
        closeList: function () {
            if (openLastItemsList.timer) {
                clearTimeout(openLastItemsList.timer)
            } else {
                lastItemsContainer.stop(false, true).fadeOut("fast");
            }
        }
    };
    

    Demo: Fiddle