Skip to content
Advertisement

JavaScript – href vs onclick for callback function on Hyperlink

I want to run a simple JavaScript function on a click without any redirection.

Is there any difference or benefit between putting the JavaScript call in the href attribute (like this):

<a href="javascript:my_function();window.print();">....</a>

vs. putting it in the onclick attribute (binding it to the onclick event)?

Advertisement

Answer

Putting the onclick within the href would offend those who believe strongly in separation of content from behavior/action. The argument is that your html content should remain focused solely on content, not on presentation or behavior.

The typical path these days is to use a javascript library (eg. jquery) and create an event handler using that library. It would look something like:

$('a').click( function(e) {e.preventDefault(); /*your_code_here;*/ return false; } );
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement