views:

36

answers:

4

Where do you personally prefer to put html tag handlers with JQuery-powered Html page and why: html tag element or document.ready function ?

<a onclick="javascript:foo()" />

...

function foo() { 
...
}

or

<a id="mytag" />

...

$(document).ready(function() {
  $("#mytag").click(function() { ... });
})

Thank you in advance!

+1  A: 

The second one, because it separates content and logic. You should never mix content (that's what HTML is for), presentation (that's what CSS is for) and logic (that's what JavaScript is for).

Delan Azabani
+1  A: 

Definitely the second one, it's much easier to maintain code when you have those 2 parts separated. Also, it looks ugly ;)

Tim
+1  A: 

for best practice's sake, in .js external files containing functions

function handleClick()
{
  $(element).click(function(e){});
}

// then call them on DOM ready with $(function(){}), this is an alternative provided by jquery equivalent to $(document).ready()

$(function(){ handleClick(); });

I do this to have a nice orderly list of functions that is easier to manage. One file, each with a couple of functions to handle the events.

So why not inline? Harder to manage, obstrusive and easier to hack (by easier to hack I mean not that much of a hassle or inconvenience to hack as I can readily modify the DOM with Firebug) compared to a compressed external JS file.

Ygam
+1  A: 

The version with the handler inside of $(document).ready is better. 1) the code use local and not global functions. It is quickly and you can access to local variables declared inside of $(document).ready functions 2) you are sure that the code of onclick function is loaded before the user able to click it. 3) It is better from the design point of view.

Oleg