Agha Agha - 3 months ago 15
Javascript Question

Javascript dealy 1 second

i am working on a mVc 3 view when i mouse-over on a div a popup come so there are lot of div's
when i mouse-over other the popup show there with differ values function is working properly i just want to add delay on the mouse-over 1 second deal without calling other function

//Display a named menu, at the position of another object
function display_menu(parent, named) {
//get the named menu
var menu_element = document.getElementById(named);
//override the 'display:none;' style attribute
menu_element.style.display = "";
//get the placement of the element that invoked the menu...
var placement = findPos(parent);
//...and put the menu there
menu_element.style.left = placement[0] + "px";
menu_element.style.top = placement[1] + "px";
}

//Hide a named menu
function hide_menu(named) {
//get the named menu
var menu_element = document.getElementById(named);
//hide it with a style attribute
menu_element.style.display = "none";
}

Answer

Add a timeout. First create a variable to hold the timer at the top, like this:

var timeout = null;

Then update the display_menu parent to operate on a timeout (my comments in the code explain):

function display_menu(parent, named) {
    // First clear any existing timeout, if there is one
    if (timeout) clearTimeout(timeout);

    // Set a timeout to open the menu after 1 second
    timeout = setTimeout(function() {
        // As we open the menu, the timer went off, so clear the timeout variable
        timeout = null;

        //get the named menu
        var menu_element = document.getElementById(named);
        //override the 'display:none;' style attribute
        menu_element.style.display = "";
        //get the placement of the element that invoked the menu...
        var placement = findPos(parent);
        //...and put the menu there
        menu_element.style.left = placement[0] + "px";
        menu_element.style.top = placement[1] + "px";
    }, 1000);
}

Finally, the logic for hide_menu:

function hide_menu(named) {
    // If a timer is running to open a menu...
    if (timeout) {
        // Nothing has yet been opened, so just stop the timer
        clearTimeout(timeout);
        timeout = null;
    // If there isn't a timer running, it's because we displayed a menu; hide it here
    } else {
        //get the named menu
        var menu_element = document.getElementById(named);
        //hide it with a style attribute
        menu_element.style.display = "none";
    }
}