Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Should Binding Event in jQuery be written in HTML or JavaScript file?

For example, In HTML

<button>Click Me</button>

If I want to binding a handler to the button, which is the following

function sayhi(){
  alert("Hello!");
}

Should I include the binding in HTML, like

<button onClick="sayhi()">Click Me</button>

or it should be written in JavaScript like

$("button").click(sayhi)

2 Answers

Andrew Dunn
Andrew Dunn
14,718 Points

I'm sure someone with more authority can express this more 'authoritatively' than me, but I'm pretty sure that person's statements will suggest you always put your Javascript in an external file, keeping your interface functionality logic all in one place, separate from the raw presentation.

Added benefits to separating Javascript and HTML in this way include:

  1. The page itself should load quicker since all your JS is housed in a separate file
  2. Search engines will be able to read your clean code much easier
  3. You will drive other developers slightly less crazy when they work with your code

Hope this is helpful - I've been chaotic in the past myself, putting Jquery/Javascript code throughout my HTML - and even dynamically building it with PHP - but I now see the terrible flaw in this.

Philip Cox
Philip Cox
14,818 Points

Hi.

Andrew is correct. We should always separate our concerns. Find the element you want the event on with javascript and then apply said event. One good reason for this is multiple events on similar elements.