Skip to content
Advertisement

how to disable a function

function function1 () {
  document.addEventListener('keyup', event => {
  if (event.code === 'Space') {
    console.log("hello world");
})
}

function onload() {
function1();
}

function function2(){
 document.addEventListener('keyup', event => {
  if (event.code === 'Space') {
    console.log("hello");
})
}
<body onload="onload()">
<button onclick="function2()">click</button>
</body>

This code will alert hello world when i press space key.

And when i execute the second function, i expect it to alert “hello” when i press space key

but it executes both function and alerts “hello world” and “hello” instead, so i was wondering how can i disable the function1() and only alert “hello” instead of executing the 2 functions when i execute the second function and press space key

Advertisement

Answer

Many issues with your code. Here we go:

  1. Do not ever use inline event listeners in your HTML like <button onclick="function2()">. It is widely considered really bad practice and has security issues. Instead, work with the DOM API and use addEventListener.
  2. Why would your button add an event listener when clicked, repeatedly if clicked multiple times?
  3. Most events are propagated throughout the DOM (that is called event bubbling), and means that when an event occurs on an element, the event is next propagated to that elements’ parent element, and so on, until the event finally reaches html (which is document). You can suppress that calling event.stopPropagation() on the event in the handler where you want to prevent bubbling.
  4. Do not use event.code since it ignores the keyboard layout of the user. Instead, work with event.key. A good site for quick keyboard event information testing is https://keycode.info/.

Please educate yourself about DOM events. https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Events

function f1(event) {
  if (event.key === ' ') {
    console.log("hello world");
  }
}

function f2(event) {
  if (event.key === ' ') {
    event.stopPropagation();
    console.log("hello");
  }
}

document.addEventListener('keyup', f1);

document.querySelector('button').addEventListener('keyup', f2);
<button>click</button>
Advertisement