DEV Community

Cover image for howto remove an eventListener
Frank Wisniewski
Frank Wisniewski

Posted on

howto remove an eventListener

first try....

<!DOCTYPE html>
<html lang=de>
<meta charset=UTF-8>
<title>CSV2Table</title>
<link rel=stylesheet 
href="https://unpkg.com/@picocss/pico@latest/css/pico.min.css">
<style>
  .fat-red{font-weight:bold; color:red;}
  button{width:200px;}
</style>

<div class=container>
<hgroup>
  <h1>EventListener</h1>
  <h2>how to remove</h2>
</hgroup>
<p>click me to get fat and red!</p>
  <button>remove Event</button>
</div>
<script>
"use strict";
var paragraph = document.querySelector("p");
var button = document.querySelector("button");
// lets add an eventListener to the paragraph,
paragraph.addEventListener("click", 
  (evt) => evt.target.classList.toggle("fat-red"))
// an eventListener to the button
button.addEventListener("click",
  () => paragraph.removeEventListener("click", 
       (evt) => evt.target.classList.toggle("fat-red")))
</script>
Enter fullscreen mode Exit fullscreen mode

sample view

OK, that doesn't work

second try....

"use strict";
var paragraph = document.querySelector("p");
var button = document.querySelector("button");
const fatRed = evt => evt.target.classList.toggle("fat-red")
paragraph.addEventListener("click", fatRed)
button.addEventListener("click",
  () => paragraph.removeEventListener("click", fatRed))
Enter fullscreen mode Exit fullscreen mode

OK, that's work...

third try...

"use strict";
var paragraph = document.querySelector("p");
var button = document.querySelector("button");
function fatRed(evt){evt.target.classList.toggle("fat-red")} 
paragraph.addEventListener("click", fatRed)
button.addEventListener("click",
  () => paragraph.removeEventListener("click", fatRed))
Enter fullscreen mode Exit fullscreen mode

it's working also ...

It's better not to use anonymous functions for eventListener(s) !!

Top comments (0)