JavaScript: Add and Remove an Event Listener (Mouseover, Mouseout)

Claudia Borghini
2 min readSep 3, 2020

--

As a Software Engineering student at Flatiron School, I am now studying JavaScript, and I’m having a lot of fun exploring all the cool things I can do with it, especially with the .addEventListener function.

Mouseover

As shown in the example below, we can make things happen when we hover onto something with our cursor, for example we can change the color of a particular word, or section.

Mouseout

However, when we move away from that particular word or section, its style doesn’t automatically change to what it was before, unless we tell it to.
We can do so with another event listener function, that is triggered with ‘mouseout’.

HTML:

<h1> Let's try some mouse events in Javascript </h1>

JAVASCRIPT:

let h1 = document.querySelector('h1')h1.addEventListener('mouseover', function(){
h1.style.color = "blue"
})
h1.addEventListener('mouseout', function(){
h1.style.color = "black"
})

The HTML of this webpage has an h1 tag with the title of this blog as innerText.
Copy and Paste the JavaScript code in your console to see how it looks like!

Remove Event Listener

Another way to remove the event is the .removeEventListener function.

Important: the .removeEventListener needs to have the same arguments of the .addEventListener that we are trying to remove. That includes the callback function, which needs to be the exact same function, not another function with the same code.

Not working code:

let h1 = document.querySelector('h1')h1.addEventListener('mouseover', function(){
h1.style.color = "blue"
})
h1.removeEventListener('mouseover', function(){
h1.style.color = "blue"
})
// the .removeEventListener is running an anonymous function that has the same code as the other anonymous function of the addEventListener, however, these are TWO DIFFERENT FUNCTIONS.

Working code:

let h1 = document.querySelector('h1')
h1.addEventListener('mouseover', blueText)

h1.addEventListener('mouseout', blackText)

h1.addEventListener('click', myRemoveFunct)

function myRemoveFunct() {
h1.removeEventListener('mouseover', blueText)
}
function blueText(){
h1.style.color = "blue"
}
function blackText(){
h1.style.color = "black"
}

Copy and Paste the JavaScript code in your console to see how it looks like!
Happy coding!

--

--

Responses (1)