Ωmega Ωmega - 6 months ago 13
HTML Question

Disable onclick with CSS :: Possible?

I would like to disable

onclick
event with CSS. Possible?

Let's say I have

<div id="btnCopy" class="button" onclick="btnCopy(this);"><img src="copy.png"></div>


and by adding class "disabled"

document.getElementById("btnCopy").className += " disabled";


I would like to turn off onclick event for this element, so
onclick="btnCopy(this);"
would not be active.

And by removing "disabled" class

document.getElementById("btnCopy").className =
document.getElementById("btnCopy").className.replace(/(?:^|\s)disabled(?!\S)/, '');


it would go back to normal, so
onclick
event will be active.

Answer

Add some Javascript to your btnCopy function to check if the parameter-element has the disabled class or not.

Using CSS to alter the behavior of JavaScript is not possible. CSS is for styling HTML elements, JavaScript is for handling the behavior of events and the site. CSS and JavaScript are two very different things. The only thing that is possible with CSS is to prevent a user from clicking on an input (button for example). With the CSS solution, you are not disabling the code in the onclick event. You are only disabling the user's ability to trigger the onclick event.

However, there are many ways to alter stuff on a page (using even more JavaScript or with some plugins for your browser), which could make it possible to click on the button despite your CSS pseudo-element. That is why using CSS for this is not recommended.

Comments