How to make a JavaScript button inactive

Learn how to deactivate a JavaScript button with an example—including disabling the button, preventing double-clicks, and more.

Making a JavaScript Button Inactive

Making a JavaScript button inactive is relatively straightforward. All you need to do is add a few lines of code to the button's onclick attribute.


var btn = document.getElementById("myBtn");
btn.onclick = function() {
    btn.disabled = true;
    //Other code
}

This code will get a reference to the button with the id myBtn and then set its onclick property to a function that sets the disabled property to true. This will make the button inactive and the user will no longer be able to click on it.

It is also possible to make the button inactive using a CSS class. This is done by adding the disabled class to the button's classList. The code would look something like this:


var btn = document.getElementById("myBtn");
btn.onclick = function() {
    btn.classList.add("disabled");
    //Other code
}

This code will get a reference to the button with the id myBtn and then set its onclick property to a function that adds the disabled class to the button's classList. This will make the button inactive and the user will no longer be able to click on it.

It is also possible to make the button inactive using JavaScript and a disabled attribute. This is done by adding the disabled attribute to the button. The code would look something like this:


var btn = document.getElementById("myBtn");
btn.onclick = function() {
    btn.setAttribute("disabled", "disabled");
    //Other code
}

This code will get a reference to the button with the id myBtn and then set its onclick property to a function that sets the disabled attribute on the button. This will make the button inactive and the user will no longer be able to click on it.

Making a JavaScript button inactive is a relatively simple process that can be accomplished with a few lines of code. The best method for making a button inactive will depend on the particular situation, but all of the above methods are valid and can be used to make a button inactive.

Answers (0)