Is it possible to disable onclick without altering its function?
You can do it in css.
<button onclick="alert('clicked')">Can click</button>
<button onclick="alert('clicked')" style="pointer-events: none;">Cannot click</button>
Pro: it works on all HTML elements
Con: it doesn't prevent keyboard action
Use the disabled
attribute to disable a button.
<button onclick="alert('clicked')">Enabled</button>
<button onclick="alert('clicked')" disabled>Disabled</button>
The advantage of this method (over the "pointer events" suggested in an alternative answer) is that it will not only stop you using the button as a mouse user, but will also stop assistive technologies and anyone using the keyboard.
In JavaScript, you can disable or enable the attribute with:
el.disabled = true; // Disable.
el.disabled = false; // Enable.
Or with jQuery you can do:
$('button').prop('disabled', true); // Disable.
$('button').prop('disabled', false); // Enable.
You can do it like this
<button onclick="false && alert('clicked')">Try Click (Disabled)</button>
<button onclick="true && alert('clicked')">Try Click (Enabled)</button>
It will work for both click event and keypress event.
<button onclick="false && alert('clicked')">Try Click (Disabled)</button>
<button onclick="true && alert('clicked')">Try Click (Enabled)</button>