Software, your way.
burger menu icon
WillMaster

WillMaster > LibraryTutorials and Answers

FREE! Coding tips, tricks, and treasures.

Possibilities weekly ezine

Get the weekly email website developers read:

 

Your email address

name@example.com
YES! Send Possibilities every week!

Using the Onclick Attribute

Learn what an "onclick attribute" is, what it does, and how to make it work for you.

The onclick attribute determines what is run when a click occurs. The click can cause any JavaScript to run, from displaying a "hello" message to making an Ajax connection with the server.

An image, content within a div, link text, text within a span tag, form buttons – pretty much any HTML tag with content can have the onclick attribute.

This is a teach-with-examples article. There are a number of examples followed by the code to reproduce it. But first, let's see what an onclick attribute actually looks like.

Some knowledge of JavaScript is helpful to understand this article. However, even if you don't understand all the code, it will still work.

What the Onclick Attribute Looks Like

The onclick attribute looks like this:

onclick="FunctionName()"

The value of the onclick attribute doesn't need to be a function. It can be any JavaScript command or series of commands:

onclick="var i = 3 * 3;"

If a function or command expects parameters that must be quoted, use single quotes so they won't interfere with the double quotes surrounding the onclick value:

onclick="FunctionName('one','two')"

A series of commands or functions can be run with the onclick attribute:

onclick="var i = 3 * 3; alert('Result=' + i)"

Some Onclick Attribute Examples

Willmaster logo

Here is the first example. Clicking on the image at the left launches an alert box with a 'You clicked on the image :-]' message.

And here is the code for that example.

<img 
   src="//www.willmaster.com/images/wmlogo_icon.gif" 
   style="height:50px; width:50px; border:none;" 
   onclick="alert('You clicked on the image :-]')" 
   alt="Willmaster logo">
   

You see how the onclick attribute works. Put it into an HTML tag and specify the JavaScript function or command to run when the image is clicked.

The onclick attribute can be put into img, a, input, button, div, span, pre, and other HTML tags used to publish content.

Here is another example. The bordered div has an onclick attribute to launch an alert box when anywhere within the div is clicked.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis vel nulla turpis, vel tempus dui. Quisque rhoncus pretium mi, eget tempus quam convallis sed.

Here is the code for the latest example.

<div
   onclick="alert('You clicked somewhere within the div!')" 
   style="border:1px solid black; padding:25px;
          width:200px;
          margin:0 auto 0 auto;">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis vel nulla turpis, vel tempus dui. Quisque rhoncus pretium mi, eget tempus quam convallis sed.
</div>

The next example is a div with the same content as the one above. The onclick attribute value is different, however. Instead of only an alert box, the onclick attribute calls a function that (i) determines how many characters, including white space, are in the div and then (ii) launches an alert box with the answer.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis vel nulla turpis, vel tempus dui. Quisque rhoncus pretium mi, eget tempus quam convallis sed.

Here is the code.

<div
   onclick="RespondWithNumberOfCharacters(this)" 
   style="border:1px solid black; padding:25px;
          width:200px;
          margin:0 auto 0 auto;">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis vel nulla turpis, vel tempus dui. Quisque rhoncus pretium mi, eget tempus quam convallis sed.
</div>

<script type="text/javascript">
function RespondWithNumberOfCharacters(div)
{
   var i = div.innerHTML.length;
   alert("Number of characters: " + i);
}
</script>

Onclick Attribute Return Values

Generally, the onclick attribute will ignore any values returned by the function. However, in at least two instances it does not.

Instance 1 —

If the onclick attribute is used in an "a" tag for linking, a return with a true or false value is required. If a false value is returned, the link is disabled for that click. If a true value is returned, the link click process proceeds according to the value of the href attribute. Example:

Link text

The onclick attribute explicitly returns the value from the custom function AlertWithReturnValue() to the "a" tag. Because this example returns a false value, the browser never goes to the destination specified in the href attribute.

Keeping the browser from going to the destination specified in the href attribute can be useful when, as examples, sending the browser to a different destination via JavaScript, the href value is a bookmark to a different section of the page and the user has already been there, the destination is strictly for spiders and JavaScript-disabled browsers, or limiting page views (perhaps counted by cookie).

Here is the code for the above example.

<a 
   href="//www.willmaster.com/" 
   onclick="return AlertWithReturnValue()">
Link text
</a>

<script type="text/javascript">
function AlertWithReturnValue()
{
   alert("The link was clicked!");
   return false;
}
</script>

Instance 2 —

If an onclick attribute is put into a form submit button tag, a return value is optional; however, if a false value is returned it will prevent submission of the form. Example:

The onclick attribute explicitly returns the value from the custom function AlertWhenSubmitButtonClicked() to the "input" tag. Because the returned value is false, the form won't submit.

Preventing the form from submitting is essential when JavaScript has detected errors in the data provided by the user. It is also a useful technique when using Ajax instead of the form for spam prevention.

Here is the code for the above example.

<form action="https://www.willmaster.com/t/dump.php">
<input 
   type="submit" 
   onclick="return AlertWhenSubmitButtonClicked()" 
   value="Click to test">
</form>

<script type="text/javascript">
function AlertWhenSubmitButtonClicked()
{
   alert("The submit button was clicked!");
   return false;
}
</script>

The onclick attribute is actually fairly simple to use once you know how. Put the attribute into an HTML tag and give the attribute a value of one or more JavaScript functions or commands to execute.

More Onclick Attribute Information

These two articles contain additional information with examples using the onclick attribute.

If you found this article useful, click one of the social media buttons below to spread the word about its existence.

Will Bontrager

Was this article helpful to you?
(anonymous form)

Support This Website

Some of our support is from people like you who see the value of all that's offered for FREE at this website.

"Yes, let me contribute."

Amount (USD):

Tap to Choose
Contribution
Method

All information in WillMaster Library articles is presented AS-IS.

We only suggest and recommend what we believe is of value. As remuneration for the time and research involved to provide quality links, we generally use affiliate links when we can. Whenever we link to something not our own, you should assume they are affiliate links or that we benefit in some way.

How Can We Help You? balloons
How Can We Help You?
bullet Custom Programming
bullet Ready-Made Software
bullet Technical Support
bullet Possibilities Newsletter
bullet Website "How-To" Info
bullet Useful Information List

© 1998-2001 William and Mari Bontrager
© 2001-2011 Bontrager Connection, LLC
© 2011-2024 Will Bontrager Software LLC