How to Add and Remove Event Listener in Javascript

In this video tutorial, you will learn how to add and remove event listener in javascript. We are going to use mouseup event for demonstration. We will simply add and remove this event on button click.

HTML:

<!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">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>
<body>
    
    <div>
        <button id="add">Add</button>
        <button id="remove">Remove</button>
        <h1>Output</h1>
    </div>

    <script src="script.js"></script>
</body>
</html>

 

CSS:

body {
    text-align: center;
}

div {
    display: inline-block;
}

button {
    padding: 10px 20px;
}

 

Javascript:

let btnAdd = document.querySelector('#add');
let btnRemove = document.querySelector('#remove');
let output = document.querySelector('h1');

btnAdd.addEventListener('click', () => {
    document.addEventListener('mousemove', handleEvent);
});

btnRemove.addEventListener('click', () => {
    document.removeEventListener('mousemove', handleEvent);
});

function handleEvent(e){
    output.innerText = `X: ${e.pageX} - Y: ${e.pageY}`;
};

 

  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •