Executing Javascript OnClick Events

I do a lot of onClick events and I hate the pound. I never had the interest to really evaluate this further, but I figured while waiting for code to compile I would do some research.
 
First what works for client side execution and what are the issues
 
<a href="#" onClick="javascript: alert(‘Hello Wold’)">Click Me</a>
This option is to use the pound in the href to make the browser think that it is a bookmark. In turn after the link is executed the OnClick event is fired causing the alert window. Works great until you have a long page and suddenly the page scrolls to the top, not what you wanted.
 
<a href="javascript: alert(‘Hello World’)">Click Me</a>
This option is to use javascript in the href attribute. This will only work in IE.
 
<a href="javascript: alert(‘Hello Word’)" onClick="javascript: alert(‘Hello Word’)">Click Me</a>
This option is to use the javascript in both the href and onclick attributes. This will work for all browsers however, duplicating code like this can be annoying.
 
<a href="#" onClick="javascript: alert(‘Hello World’); return false;">Click Me</a>
This option is to use the href and the onclick attributes however in the onClick event, tell the browser to disregard the click. This technique goes back to the ability to stop a form from submitting after you click the submit button. This will remove the issue seen in option 1.
 
This entry was posted in Development. Bookmark the permalink.

Leave a comment