OnClick - HTML Event Attribute

The OnClick event attribute controls what happens if a HTML element is clicked.

Edited: 2017-12-11 04:53

The onClick event attribute is used to catch the click event of a pointing device, but is also used for touch devices.

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 downs, it is important that you allow menus to close once clicked a second time, since it can otherwise get "stuck" in a folded-out state.