Skip to main content

onclick (HTML Attribute)

By Ophelie Lechat

HTML & CSS

Share:

Free JavaScript Book!

Write powerful, clean and maintainable JavaScript.

RRP $11.95

Description

The
onclick event handler captures a click event from
the users’ mouse button on the element to which the
onclick attribute is applied. This action usually
results in a call to a script method such as a JavaScript function, like
this:

onclick="displayHelpInfo();"

However, it can
also be used to run a script in situ:

onclick="alert('You are clicking on me');"

Note that this event attribute cannot be applied to the following elements:

  • applet
  • base
  • basefont
  • bdo
  • br
  • font
  • frame
  • frameset
  • head
  • html
  • iframe
  • isindex
  • meta
  • param
  • script
  • style
  • title

Example

Clicking anywhere on the
div below will call a function, defined elsewhere,
called showStats():

<div onclick="showStats();">Figures for February’s racing.</div>

Value

This attribute has no fixed value.
It’s up to the author to decide on the scripting that’s included here, be
that a call to one or more defined functions, or a simple
alert() statement.

However, the likely values will be similar to
this:

onclick="doMyFunction();"

You
could also specify a value like this:

onclick="doThisFunction();thenDoTheOtherFunction();"

You
may also use a value like this:

onclick="alert('Hello world');window.close();"

Note
that you can string several functions together, separating them with a
semicolon, as shown in the second and third examples
above.

Compatibility

Internet Explorer Firefox Safari Opera
5.5 6.0 7.0 1.0 1.5 2.0 1.3 2.0 3.0 9.2 9.5
Full Full Full Full Full Full Full Full Full Full Full

Every browser listed supports this
attribute. However, inline event handlers such as this should be avoided.
In the same way that inline CSS styles are frowned upon but externally
defined CSS styles are considered good practice, inline event handlers
should be stripped out and replaced with events attached unobtrusively
through the DOM.

Ophelie was Head of Content at SitePoint and SitePoint Premium. She also runs ophelielechat.com.

New books out now!

Learn how Git works, and how to use it to streamline your workflow!


Google, Netflix and ILM are Python users. Maybe you should too?