views:

66

answers:

3

I have been using Jquery alot lately an was wondering if I should use listeners or functions for my clicks.

Normally I do the following:

<head>   
  <script type="text/javascipt">
    function buttonclicked() {
    alert("You Clicked it");
  }
  </script>
</head>


<button onclick="buttonclicked()">Click Me</button>
+2  A: 

Benefits of using listeners also allow you to separate your markup and JavaScript.

alex
Thanks, for the info.
dweebsonduty
@alex, If you are using a JS templating engine to generate your HTML, your markup and JS are separated too. And IMO, I find it easier to debug/maintain the code as you see it while inspecting the page.
Mic
@mic. They both have their benefits and drawbacks.
alex
+1  A: 

i think its more efficient to do what you did in your example.

Also, i wouldnt do that since it is not that much more efficient that it would matter, and it makes for ugly code. Also its better to separate your js from your html.

So please dont do what you did in your example unless you have a very good reason

mkoryak
Thanks, for the info.
dweebsonduty
+2  A: 

Reasons that it's better to use the jQuery event mechanism and not the "intrusive" onfoo element attributes:

  • You can take advantage of the "live" mechanism. If your interest is efficiency, then this is something you definitely should be thinking about.
  • Disjoint pieces of code can bind handlers to the same elements for different reasons without even having to know about eachother. You don't have to update a single handler to deal with everything.
  • You keep your markup much cleaner, and save a lot of trouble when event handling needs to change. If you bind handlers based on (for example) element class ("button.showHelpText" for example) then radical changes to your "help text" code can be made without having to touch the HTML markup at all.
  • You avoid the unsightly mess of polluting the global Javascript namespace with all those global handler functions.
  • You have solid, dependable access to the "event" data, courtesy of the jQuery framework.

Overall, if you're going to use jQuery, dive in and really use it.

Pointy
+1 great answer.
alex