onclick attribute vs eventListeners - javascript

I'm re-writing the code of a website I created a few years ago, and I was wondering what was the most efficient way to handle the click event on an element?
I have a list of items with links to edit them, and they're all written with the onclick="..." HTML attribute. Is it better that way or I should use $.bind() or addEventListener to handle it? What's the best practice?

It is considered best practice to utilize what is called unobtrusive javascript. What this means is you separate the layout of your HTML from the behavior of the elements. So instead of using the onclick attribute, which mixes up element structure and behaviour, you layout your DOM structure in markup and then attached event handlers via javascript.
What this means is that is considered best practice to use javascript to attached event handlers, as follows:
<html>
<script>
... bind event handlers to your DOM and set behaviours here
</script>
<body>
.... layout your DOM here
</body>
<html>
This has advantages for long-term code maintainability and extensibility. This approach works very nicely with javascript libraries such as jQuery.
In terms of performance, you may be able to achieve performance gains via an unobtrusive javascript approach by using an intelligent caching strategy.
For more information on unobtrusive javascript, see here

addEventListener or it's jQuery version on \ bind is the best practice as it separates the visual part-HTML from the functional part- javascript.
Separates of concerns.
If the code is written already, I wouldn't change it, it's not that important.

Many people will discourage the use of onclick because "what if you want to add another onclick event?" - personally I have never had this issue, but I can sort of understand.
If you're not using the links for anything other than a single click event, then onclick is perfectly fine. However, if you want it to be bulletproof, you probably want addEventListener. I actually have my own addEvent/fireEvent/removeEvent trio of functions that keep track of events and handle browser inconsistencies for me (bringing in window.event, for instance) and this works quite well.

Related

What's the difference between .click(function () { and javascript:myfunction()?

Consider the simple link below:
Link
I understand there are two ways to run a function when a user clicks this element:
$(".mylink").click(function () {
and
Link
Is there a performance difference between the two, or any other practical reason I should use one over the other?
Using $('.mylink').click(function(){ is better as it follows standard event registration model. (jQuery internally uses addEventListener and attachEvent).
Basically registering an event in modern way is the unobtrusive way of handling events. Also to register more than one event listener for the target you can call addEventListener() for the same target.
Read jQuery.click() vs onClick
and How does inline Javascript (in HTML) work?
https://softwareengineering.stackexchange.com/questions/86589/why-should-i-avoid-inline-scripting
They have the same functional behavior, there is no difference whatsoever.
The difference is in code modularity and maintainability.
Using the first method is preferred and more appropriate because it doesn't mix between HTML and JavaScript, a concept called Unobtrusive JavaScript.
If you have worked in the early days of HTML, then you should remember when there were all those attributes like background, color, font ... etc.
Then CSS came in, and everybody told us not to use those old attributes anymore because they mix presentation with document structure, instead we should use CSS to control layout and look of the document.
This is similar to that idea but it is now used for code, separate functionality from document structure.
Edit: Quoting from #mplungjan comment in order to be more accurate:
That there is no difference is not true. href="javascript:myFunction()" does not have the ability to cancel the actual click with a preventDefault or return false. Hence animated gifs will stop running in some browsers and older browsers would even partially unload the page. Also if the function returned a value, the page would be replaced with that value, seen when beginners try href="javascript:window.open..." and get [object object] on the page
Jquery like any other good JavaScript frameworks supplies you with functionality independent of browser platform wrapping all the intricacies, which you may not care about or don't want to care about.
I think using a framework is better instead of using pure JavaScript and doing all the stuff from scratch, unless you usage is very limited.
I definitely recommend JQuery!
The first one is JQuery convention of an event listener. You need to include jquery library in order to use it. The second one is a Javascript convention. You don't need to include any library or extra code to run. There are no differences in terms of performance, but as I told if you do not want to include any kind of library you should use the second example.

Why are more people nowadays using script to assign events handlers vs assigning the event from within the html element?

As a learner I like to look at lots of source code. Since I started learning JavaScript about a year ago, I notice a trend of people not using traditional event handlers as in onclick="doSomething()", but are more and more using methods like document.getElementById("someId").onclick = function(){..some code..};
What's the reason behind this trend?
Assigning the handlers in Javascript puts all of the code in one place instead of scattering it throughout the HTML.
This helps separate content from script, just like CSS helps separate content from style.
It's also faster, since the browser won't need to fire up a Javascript parser for each handler attribute.
This is an example of Unobtrusive Javascript.
The other answers haven't touched on this, so:
Your example uses the (reflected) onclick attribute even in the JavaScript code:
document.getElemenbyId("someId").onclick = function(){..some code..};
...which for me misses out one of the primary reasons for doing this without using attributes: Playing nicely with others. The DOM2 way of attaching handlers (addEventListener, or attachEvent on IE [IE9 has the standard addEventListener finally]):
document.getElementById("someId").addEventListener("click", function() { ... }, false);
// or
document.getElementById("someId").attachEvent("onclick", function() { ... });
... is non-exclusive — more than one handler can be attached at the same time. Whereas if you assign to onclick, you're kicking any previous handler off and taking over.
To me, this "playing nicely" thing is a big sell. Well, that and keeping code and markup separate, but that's been well-covered in other answers.
HTML should be only markup, pure content.
Design should be in CSS style sheet.
Dynamic scripting should be in JavaScript code, separate file is good.
Just feels better and looks better - as far as I can tell it's not more efficient just more elegant and easier to maintain when all the script is in one place instead of being spread all across the HTML. :)
As mentioned by other answers, the main reason is separation of concerns (in this case, keeping behaviour separate from content), which is entirely sensible. However, that isn't always the only consideration. I've previously written a lengthy answer to a related question.
I think most people are using jQuery. $("#someId").click(function(){}) and when you want to attach an event to many elements jQuery makes it easy and puts your function in one place.

Is there a difference between placing JavaScript calls in $(document).ready(function(){ and placing them in HTML?

Is there a difference, performance or efficiency wise, between placing javascript calls such as blur, onclick etc. in $(document).ready(function(){ as opposed to placing them in HTML?
Thanks!
I think by "in the DOM" you mean this:
<a href='#' onclick='someCodeHere()'>Click Me</a>
right? If so, then it's not so much about performance as it is about maintainability and power. Using jQuery (since you mentioned the "ready" handler in jQuery terms) to bind your events lets the framework take care of managing multiple handlers, and dealing with browser differences.
In fact sometimes it's even better to not bind directly to elements at all. Instead, you can use the jQuery "live" or "delegate" mechanisms to help cut down on actual handler bindings and provide for a more dynamic DOM.
I dont quite understand the meaning of placing them in DOM. But yes if you mean inside a script tag in your body. The document.ready thing executes before the images are loaded and it save time for javascript actions to take place
I agree that it is much more elegant to use jQuery or other and have unobtrusive js. This way it's all clearly visible, and easily extensible.
I just want to mention 1 quick problem that I had with all of this, and it involves generated code (i.e html from frameworks). In my case, Apache Trinidad as part of JSF. When trinidad generates HTML, it included inline javascript calls like onclick='submitForm(..)'
I was modifying the existing custom inline calls to use jQuery, for example:
<tr:commandLink onClick="doStuff()" />
which generates html like:
<a href="#" onclick="doStuff(); submitForm(..)" />
Now in the case that the javascript call is inline, if you return false from the method, the rest of the onClick will not execute. However, when using non-obtrusive jQuery, the inline method will not be stopped (not easily anyway).
I guess what I'm saying is "be weary of frameworks" :-)

What is more efficient: listeners or functions in jquery

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>
Benefits of using listeners also allow you to separate your markup and JavaScript.
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.
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

onClick w/ DOM vs. onClick hardcoded

In javascript, what are the pro's and con's of encoding an onclick event in the DOM and in the HTML itself?
Which, if either, is better than the other and why?
Your question almost answers itself when you refer to "the HTML itself".
JavaScript is not HTML -- Keeping the HTML and the JavaScript in separate locations is a benefit all by itself. Makes it easier to (humanly) read the HTML, and keeping all the JS in the same location makes it easier to track everything down all at once.
It is better to write your Javascript in Javascript, as OtherMichael says. It is even better to use proper DOM events (addEventListener and attachEvent) rather than on_____, in order to avoid conflicts and allow multiple callbacks for the same event.
Attaching events to an CSS-style ID (or classes), as Jquery does so well, means that if you don't have JS enabled, it will automatically fall through to any links that are referenced. That's good practice, and will help to make sure that your page works in even quite simple browsers, such as some mobile handsets.
It's also good practice to layer the underlying data (the HTML), presentation (CSS) and behaviour (Javascript). Changing individual layers is a lot easier if they are well structured.

Categories

Resources