OnClick - HTML Event Attribute
The OnClick event attribute controls what happens if a HTML element is clicked.
Edited: 2018-08-19 08:43
The onClick event attribute is used to catch the click event of a pointing device, but is also used for touch devices.
It might be better to use event handlers in JavaScript, rather than relying on the onClick attribute, since it allows to better separate scripting from the HTML markup.
The onClick attribute can be used to determine when a HTML element is clicked, which makes it possible to turn ordinary elements into clickable buttons. Doing this can however present usability issues, so it may be best to avoid using it on anything else than links and buttons, unless it serves a specific purpose, such as allowing a CSS-based drop down menu to also work in touch-based devices.
The below shows how to use the onclick event on a button element, to throw out a basic alert box.
<button onclick="alert('Dont poke me. Just dont. Im just not in the mood!');">Don't poke me!</button>
onClick and touch devices
onClick also works on touch devices, and it is therefor an ideal solution where CSS :hover is used. The :hover class works fine on PCs with traditional mice or touchpads, but will not work for most mobile devices, since these are touch-based.
When creating drop-down menus, it is important that you allow to close them again when clicking/touching it the second time, since it can otherwise get "stuck" in a folded-out state.
Tell us what you think: