Home > Net >  javascript onclick set to false
javascript onclick set to false

Time:10-07

document.getElementById("btn2").onclick = false;

I did this to stop getting on click event after the first one and when I want to set it back to normal

document.getElementById("btn2").onclick = True;

it does not take click events

CodePudding user response:

You could always disable the button, like this:

document.getElementById("btn2").disabled = true;

This sets the disabled attribute to true, therefore stopping the onClick function from being called when the user clicks the button.

CodePudding user response:

Declare a variable boolean and change using logical not operator (!: see in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_NOT), example:

let toggle = true;
let button = document.querySelector('button');
let result = document.querySelector('span');

button.onclick = () => {
  toggle = !toggle;
  result.textContent = `Your switch to ${toggle}`;
}
<button>Click me</button>
<span></span>

CodePudding user response:

You may not set onclick event as True instead try this way.

const setEvent = (enable) => {
 if(enable){
    document.getElementById("btn2").addEventListener('click', onClickEvent);
 }
 else{
    document.getElementById("btn2").removeEventListener('click');
 }
}

function onClickEvent(){
   //Your actual event when clicking the button
}

//Now enable or disable the event as follows
setEvent(true);  //Will attach the event
setEvent(false); //Will remove the event

Make sure you call setEvent(true) once only, because it can attach multiple events.

  • Related