Javascript onclick and ondblclick event handlers - javascript for newbies

Sponsored Links

JavaScript Event Handlers - onclick and ondblclick

When a link is clicked it takes the user to the page specified in the URL of the HREF attribute. To prevent this from happening, use javascript:void(0) as the value of HREF.

<A HREF="javascript:void(0)"
onmouseover="document.bgColor='#EEEEEE'">
Dead link</A>

Link



You may wonder why we can't use HREF="" (a blank or no value) instead of HREF="javascript:void(0)". The reason is that a blank or null value for HREF is interpreted as the URL of the directory. Thus, in our case if we use HREF="", the browser actually sees it as http://www.webdevelopersnotes.com/tutorials/javascript/.
javascript:void(0) returns (not specifies!) a null value. Hence, whenever a link is clicked no page is loaded.

Mouse clicks and event handlers

So far we have only looked at event handlers that capture mouse movements over a link. JavaScript also provides event handlers for links that understand mouse button clicks; onclick and ondblclick. Their usage is similar to other event handlers.

<A HREF="javascript:void(0)" 
onclick="alert('You clicked on the link')">
Dead link</A>

Dead link

<A HREF="javascript:void(0)" 
ondblclick="alert('You double clicked on the link')">
Double click on me</A>

Double click on me



Assignments

  1. Construct a link that changes the background color to light blue (#99CCFF) when clicked.
  2. Change the code so that clicking on the link also displays an alert box.
  3. How about a link that changes the background color to red when clicked and back to the original when the mouse pointer is moved off the link?
  4. The open() method of the window object is employed to open a new window. Construct a link that opens a new window when clicked.

Click here for possible answers



Page contents: Javascript onclick and ondblclick event handlers - javascript for newbies

AddThis Social Bookmark Button

JavaScript Tutorial