Unlocking User Experience: Creating A Perfect Disabled Button with JavaScript

Protecting Web Forms and Interactivity for a More Accessible and Engaging Experience

Photo by Pearse O’Halloran on Unsplash

If I ask you to make a <button /> disabled, Then what will be your answer?

.

.

.

.

.

Most of us will come with a solution like this:

<button disabled> Button </button> 

or

document.getElementById("Button").disabled=false;

or In React
<button
disabled={true}
>
Button
</button>

The problem with this approach is that, any one can inspect and remove the disable attribute.

disabled attribute can be removed.

To overcome this, some might suggest to block the click using CSS.

button {
pointer-events: none;
}

But CSS can also be removed.

CSS can also be removed.

In order to create a perfect disabled button , along with above listed two ways we should always add one the two listed solution below:

  1. Add check in click handler of disabled button : By doing this we will ensure that even if user has enabled then button, by changing the attribute, whenever the handler function is called, nothing will happen.
function handleClick() {

if (buttonDisabled)
return;
}

// other code

}

2. Use MutationObserver to detect attribute Change: Whenever any attribute changes, we can re-add it by using MutationObserver callback function.

Caveat: Make sure not to update the DOM in MutationCallback directly, otherwise UI will freez and application might become unresponsive.

const elem = document.getElementById("safe-button");

const observer = new MutationObserver(manageMutations);

if(elem) {
observer.observe(elem, {attributes: true});
}

function manageMutations(mutations) {
mutations.forEach(function(mutation) {
if(mutation.type === 'attributes' && mutation.target.id === 'safe-button') {
setTimeout(()=> {
mutation.target.disabled= true;
}, 0)
}
});
}

With these methods, we can only ensure that nothing malicious happen with our website. That’s why it is always advised to not depend on front end validations, we should always have server side validations in place.

--

--

राहुल मिश्रा
राहुल मिश्रा

Responses (1)