Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery: is it a good idea to use Javascript events as inline attributes?

Tags:

jquery

When reading about JQuery best practices, I read this recently:

Never include Javascript events as inline attributes. This practice should be completely wiped from your mind.

<a onclick="doSomething()" href="#">Click!</a>

Why is this? Is this interpretation? Personally, I find that JQuery is best when you need to dynamically set events, or set an event to a div. Otherwise, it allows for much cleaner code, as the inline attribute can always call a method of your choice.

btw, article in question: http://www.smashingmagazine.com/2008/09/16/jquery-examples-and-best-practices/

like image 655
KevinDeus Avatar asked May 27 '11 15:05

KevinDeus


People also ask

How do you bind events in jQuery?

As of jQuery 1.7, all events are bound via the on method, whether you call it directly or whether you use an alias/shortcut method such as bind or click, which are mapped to the on method internally.

How do I listen to events in jQuery?

There are a number of ways that events can be listened for using jQuery: // shorthand `click` method. alert ( "Hello." ); alert ( "Hello." ); // using jQuery's `on` method. alert ( "Hello." ); // clicked on the page.

What is an event object argument in jQuery?

In all DOM event callbacks, jQuery passes an event object argument which contains information about the event, such as precisely when and where it occurred, what type of event it was, which element the event occurred on, and a plethora of other information.

What is an event handler in JavaScript?

To specify to the browser what to do when an event occurs, you provide a function, also known as an event handler. This function is executed whenever the event occurs (or until the event is unbound).


1 Answers

One of the reasons why I agree with the article is it involves the separation of layers between your code. Inline code leads to sloppy, hard to maintain code. By including the script files you are reducing the amount of time used to change code / clean up code / fix bugs. If that inline function doSomething() becomes really popular across your projects that embedding it into each page can be a nightmare.

I admit I've gone against this at times, but it has bitten me in the past. I can't say I will completely change my habits 100%, but it's a good programming practice. It isn't something that I would consider wrong though. There are millions of shops out there that still do it, they will most likely do it 10 years from now. To each his own.

like image 51
JonH Avatar answered Sep 24 '22 21:09

JonH