Languages
[Edit]
EN

JavaScript - remove event with VanillaJS

6 points
Created by:
Wayne
415

In this article, we would like to show you how to remove events using VanillaJS.

Quick solutions

// 1. removeEventListener method example
   button.removeEventListener('click', onClick);

// 2. Setting event property null value example
   button.onclick = null;

// 3. Removing element attribute example
   button.removeAttribute('onclick');

// 4. jQuery examples
// https://dirask.com/q/jquery-how-to-remove-event-zjMozD

1. removeEventListener method example

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <button id="my-button">
    Click button...
  </button>
  <br /><br />
  <button onclick="removeEvent();">
    Remove click event...
  </button>
  <script>

    var button = document.getElementById('my-button');

    function onClick() {
        console.log('Event name: click');
    }

    button.addEventListener('click', onClick);

    function removeEvent() {
        button.removeEventListener('click', onClick);
    }

  </script>
</body>
</html>

2. Setting event property null value example

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <button id="my-button">
    Click button...
  </button>
  <br /><br />
  <button onclick="removeEvent();">
    Remove click event...
  </button>
  <script>

    var button = document.getElementById('my-button');

    button.onclick = function() {
        console.log('Event name: click');
    };

    function removeEvent() {
        button.onclick = null;
    }

  </script>
</body>
</html>

3. Removing element attribute example

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <script>

    function onClick() {
        console.log('Event name: click');
    }

  </script>
</head>
<body>
  <button id="my-button" onclick="onClick();">
    Click button...
  </button>
  <br /><br />
  <button onclick="removeEvent();">
    Remove click event...
  </button>
  <script>

    var button = document.getElementById('my-button');

    function removeEvent() {
        button.removeAttribute('onclick');
    }

  </script>
</body>
</html>

4. jQuery examples

How to remove events with jQuery has been described in this article.

See also

  1. jQuery - how to remove event?

Alternative titles

  1. JavaScript - how to remove event with VanillaJS?
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join