Search code examples
javascriptlistdommouseovermouseout

How do i remove the submenu using a mouseout/mouseleave event handler


I'm trying to create a submenu for a menu item, i have got as far as creating a list of items and using a mouseover event handler but the submenu just remains there. i need it to be removed once the mouse clears away from the submenu div, not the label div. The mouseover function works but the mouseout im having a problem with. I am new to using javascript and DOM

This is the code (DOM):

var creatbtndiv = document.createElement("div");
var creatbtn = document.createElement("button");
creatbtn.innerHTML = "Click Me";
var creatlbl = document.createElement("label");
creatlbl.innerHTML = "Hover Over Me ";

creatbtndiv.appendChild(creatlbl);
creatbtndiv.appendChild(creatbtn);

document.body.appendChild(creatbtndiv);



var list = function () {
    var creatDiv = document.createElement("div");
    creatDiv.id = "submenudiv";
    creatDiv.className = "submenudiv";

    var creatul = document.createElement("ul");
    for(index = 0; index < 5; ++index){
        li = document.createElement("li");
        li.className = "list";
        li.innerHTML = "Submenu" + index;
        creatul.appendChild(li);
    }

    creatDiv.appendChild(creatul);
    document.body.appendChild(creatDiv);
};
//If the cursor hovers over the label, activate this function//


creatlbl.onmouseover = function () {
    var alert = confirm("yes master");
    list();
};

creatDiv.onmouseout = function(){
    var confirm = confirm("the mouse is out");
    list.removeChild(creatDiv);
};

Solution

  • creatDiv its outside its scope, so this function does nothing:

    creatDiv.onmouseout = function(){
        //var confirm = confirm("the mouse is out");
        list.removeChild(creatDiv);
    };
    

    You could put this function, after:

    document.body.appendChild(creatDiv);
    
    creatDiv.onmouseout = function(){
        //var confirm = confirm("the mouse is out");
        this.parentNode.removeChild(this);
    };