As comment to one of the questions here a commenter wrote (emphasis mine):
... By using an inline "onclick" you are doing a similar thing, but it is harder to maintain and more prone to issues. The JavaScript community as a whole has been moving away from inline JavaScript for a while now.
This was referring to attaching events to HTML elements using:
$("#someID").click(function(){
do something here...;
});
rather than:
<a id="someID" onclick="someFunction();">
Has there really been a shift away from the old school way of declaring events inline, and if so, what are the benefits of one of the other?
EDIT I guess it may be helpful to include a reference to the original question. It asked about attaching a different click event to each tab. Is my answer crap and do I owe FallenRayne an apology =).
The big benefit is the separation of content (html) and action/behavior (javascript). This is known as Unobtrusive javascript. Keeping these separated makes it easier to change either without affecting the other.
Yes, there has, at least in some portion of the community, not sure how you'd measure it overall.
There are definitely advantages, off the top of my head:
From sheer volume, think of this:
<a onclick="someFunction();">
<a onclick="someFunction();">
<a onclick="someFunction();">
<a onclick="someFunction();">
<a onclick="someFunction();">
Or this once:
$("a").click(someFunction);
You can do this with most frameworks via a css selector, etc, handles many elements at once. This means in server code you're just assigning IDs and classes, the client side is easier to handle separately. It's easier to debug as well, for example: in the console I can do $('a').unbind('click').click(...something new...);
Another benefit is performance. If I can split this into a separate .js file, cached by the client, that's thinner webpages and extra data I'm not sending every time. Smaller web page = faster load.
Here's one more example, thinks about how simple it is, granted some framework action via jQuery going on, but how would this look with inline events?
$("li").hover(function() {
$(this).children().slideToggle();
});
Comparatively, that's a tremendous amount of inline code, even if you leave out the animation portion it's messy (think mouseenter/mouseleave, not mouseover/mouseout...the former, which .hover() uses, is more complicated)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With