简体   繁体   中英

how to stop an Event to run again in simple javascript?

My Code is below . Now what i want is that ,the event execute only on first mouseover after that it should become disable. which means if user mousover again it should do nothing ** **Thanks

HTML is below !

<div id="welcomehomebtndiv">
    <button id="welcomehomebtnteacher" type="button">Teacher</button>
    <button id="welcomehomebtnstudent" type="button">Student</button>
    </div>

actual function is this !

document.getElementById("welcomehomebtnteacher").addEventListener("mouseover", removebtn);

    function removebtn() {
        var parent = document.getElementById("welcomehomebtnteacher");
        var child = document.getElementById("welcomehomebtnstudent");
        parent.removeChild(child);
}

In the event listerer just unbind the event;

function removebtn(e) {
    e.target.removeEventListener('mouseover', removebtn);
    ...
}

The most obvious solution is to add a flag and check if it's already raised or not:

var childRemoved = false;
document.getElementById("welcomehomebtnteacher").addEventListener("mouseover", removebtn);

function removebtn() {
    if (!childRemoved) {
      var parent = document.getElementById("welcomehomebtnteacher");
      var child = document.getElementById("welcomehomebtnstudent");
      parent.removeChild(child);
      childRemoved = true;
    }
}

The Teacher button will be disabled & will NOT REMOVE THE BUTTON .Hope this your criteria.If this is so you can use disabled=true;

document.getElementById("welcomehomebtnteacher").addEventListener("mouseover", removebtn);
function removebtn() {
     document.getElementById("welcomehomebtnteacher").disabled =true;
 }

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM