OnClick - HTML Event Attribute

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

1268 views

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:

  1. An in-dept look at the use of headings (h1-h6) and sections in HTML pages.
  2. Pagination can be a confusing thing to get right both practically and programmatically. I have put a lot of thought into this subject, and here I am giving you a few of the ideas I have been working with.
  3. The best way to deal with a trailing question mark is probably just to make it a bad request, because it is a very odd thing to find in a request URL.
  4. How to optimize image-loading and automatically include width and height attributes on img elements with PHP.
  5. HTTP headers are not case-sensitive, so we are free to convert them to all-lowercase in our applications.

More in: Web development