gorootde
gorootde

Reputation: 4073

What is the best method to bind an JS event to a link?

What is the best way and why?

Href?

<a href="javascript:helloworld()">link</a>

onclick?

<a href="#" onClick="helloworld()">link</a>

bind by framework (e.g. jquery)?

<a id="foo" href="#">link</a>
…
$('#foo').live('click',helloworld);

Upvotes: 2

Views: 300

Answers (4)

Duglas
Duglas

Reputation: 251

Don't use javaScript in HTML markup!

$(function() {
   var foo = $('#foo');

   if(foo[0]) {
      foo.click(function(event) {
          //..
          event.preventDefault();
      });
   }
});

or use on() since jQuery 1.7+

foo.on('click', function(event) {
   //..
   event.preventDefault();
});

Also don't use live() never (As of jQuery 1.7, the .live() method is deprecated)!

Upvotes: 0

Ry-
Ry-

Reputation: 224856

It depends. Usually, you should never have a link that does nothing. What if your users have JavaScript disabled, or it fails to load? You must degrade gracefully to have an accessible website. So, for example, if you have a box that loads with Ajax, you should have it link to an alternative page, then bind the handler in unobtrusive, separate JavaScript:

<a class="loadPage" href="actualPage.php">Go to my page</a>

and in another file:

$('.loadPage').click(function(e) {
    // Load with Ajax...
    e.preventDefault(); // Stop the link from going through
});

If the links were generated with JavaScript, then it's okay to use # as an href most of the time. However, in that case, you should still be attaching the handlers with JavaScript as opposed to setting onclick in innerHTML (*shudder*).

So, generally: if you have an onclick attribute or javascript: link in production code, right in your HTML, you're not separating content, behaviour and presentation; you're not being accessible; and you're not being semantic. Don't do it!

Upvotes: 3

Segev -CJ- Shmueli
Segev -CJ- Shmueli

Reputation: 1621

Do not use 'javascript:myaction()' .

Always prefer the usage of a framework, as it create a real bind (meaning registering the event with the browser window). So the best way to go is : $('#foo').live('click',function(){my action.... });

it will also allow you to keep your javascript in a separate file, which is the best practices for dealing with scripts.

the second best way to go is using the onClick event.

Upvotes: 0

Quentin
Quentin

Reputation: 943142

None of the above.

You should keep the JS in an external file (separation of concerns makes for more manageable and reusable code), and using a library does smooth over the differences between browsers that support standard event binding and older versions of Internet Explorer.

However, JavaScript should be unobtrusive. You should not start out with a link to the top of the page.

Upvotes: 2

Related Questions