JavaScript - details of addeventlistener and removeEventListener

addEventListener(), removeEventListener(), are event binding operations. One is to add event binding, the other is to remove event binding.

addEventListener() is used to add binding events to the element, and removeEventListener() is used to remove binding events from the element.

Syntax description:

element.addEventListener(event,fn,useCaption ); 
Parameter Description: event, such as click mouseenter mouseleave
fn callback function

useCaption is used to describe whether it is bubbling or catching. The default value is false, i.e. bubbling transfer, and when the value is true, i.e. capturing transfer.  

Example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <button id = "btn-add">Add to</button>
    <button id = "btn-remove">Remove add button's mouseover Event</button>
    <script type="text/javascript">
    /*
        W3C  Event binding.
        addEventListener(Event name, event handler, false)
        removeEventListener(Event name, event handler, false)
        Note: the event handler must be a function.
        For example: removeEventListener is written in function() {}
        
    */
    var btnadd = document.getElementById('btn-add');
    var btnremove = document.getElementById('btn-remove');

    btnadd.addEventListener("click",function(){
        alert('dsafasdf')
        },false);

    btnadd.addEventListener('mouseover',show,false);




    btnremove.addEventListener("click",function(){
        //Add btnadd's undo mouseover event to btnremove's click event.
        btnadd.removeEventListener("mouseover",show,false);
    },false)

    function show(){
        console.log('hello');
    }

    </script>
</body>
</html>
Note: removeEventListener() cannot remove anonymous functions, only parameters with names can be used, such as show() above

Keywords: IE Javascript

Added by ven0mblade on Sat, 15 Feb 2020 19:54:35 +0200