Languages
[Edit]
EN

JavaScript - how to remove event with VanillaJS?

6 points
Created by:
Kate_C
19810

In JavaScript it is possible to remove event in following way.

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?
Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join