2

If I have below button :

<button type="button" id="send_email" class="btn btn-primary" 
onclick="sendEmail();">Send</button>

So, which is better calling JS function or using click event in separate JS file

function sendEmail(){
  ..... some code  .....
}

OR

 $("#send_email").click(function(){});
Pravesh Mehta
  • 228
  • 1
  • 9
  • 1
    the first one doesn't require any external library its written in pure javascript. Also it is inline javascript. but the second one you have given requires an external library jquery(any way it can be done in pure javascript with event handlers ). http://stackoverflow.com/questions/6348494/addeventlistener-vs-onclick – Tintu C Raju Jan 19 '16 at 08:14
  • @tintu-c-raju I think the question is asking in principle, using jQuery or not. – DvS Jan 19 '16 at 08:15
  • @DvS ya.... your answer addressed it well :-) – Tintu C Raju Jan 19 '16 at 08:20

3 Answers3

2

second one

$("#send_email").click(function(){});

is better because

  • it is obtrusive and hence better for accessibility, read more about it here

  • it makes the code more readable and maintainable since it separates structure from logic.

gurvinder372
  • 66,980
  • 10
  • 72
  • 94
2

I would chooose the second option over the first for the following reasons:

  1. Keeps your JS separate from the HTML
  2. Easier to develop thanks to jQuery. Development time reduced.
  3. Easier to add effects and other animations
  4. Better browser compatibility
  5. Extra complexity with less code

However, if your application is not going to require a lot of scripting, I would go for pure JavaScript. Reason is it is going to cost extra time to load the jQuery source file.

Marco V
  • 2,553
  • 8
  • 36
  • 58
1

It is widely considered better to register with an element's events as in your second option. Some call this 'unobtrusive javascript'.

It's functionally equivalent, but it helps to separate HTML and javascript code, making it cleaner and easier to maintain and deploy. You can also incorporate the handling of the event in the scope of a greater function(ality).

DvS
  • 1,025
  • 6
  • 11