8

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/

6
  • 2
    Well you can dynamically bind an action to a div like so: $('#divId').bind('click', function(){}), and I've heard this view pushed for not just JQUERY but also javascript in general, but never the explanation to why. I'm interested in finding out why. Commented May 27, 2011 at 15:27
  • 2
    Never use a hammer to put a nail in. Always get the nail gun out. Equally silly. Commented May 27, 2011 at 15:27
  • 2
    Use in-line javascript if you want to, and if your project or environment allows it. It's no ones business what you do on your own projects. A lot of people prefer to keep the javascript separate from the markup, and that's how it got labeled best practice, the abstraction of display from logic. Commented May 27, 2011 at 15:28
  • 2
    Nobody is telling you that you can't do that. Best practices exist to help you; not to make things difficult. Inline is not recommended because of scalability issues. You may not think what you are doing will ever need to be maintained or expanded but if it does then you've definitely just increased your headaches if you scripted inline handlers. Of course the choice is always yours. Commented May 27, 2011 at 15:35
  • Its actually a nice topic / article, why would you want to close the topic ? Commented May 27, 2011 at 15:38

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

0

The main reason inline events are not recommended is that they are very difficult to maintain. Generally, you should place all your javascript in a separate file (there are cases where "inlining" your javascript/css/images is beneficial to performance).

Also, you have to remember that jQuery is just javascript. So, any article implying that every event should always be bound via jQuery is silly. However, if you already have jQuery loaded it is probably a pretty good idea to use it as it takes care of many of cross-browser issues that may arise.

Now to do this in pure javascript, in a more maintainable fashion, you can always:

document.getElementById("hello").onclick = function(){
    // p.s. I clobber any previous onclick handlers 
    // that may have been assigned to this element.
    // Sure, there are ways around this. But they are lame.
    /* If you use this method of event binding in an    */
    /* application/site make sure you don't include     */
    /* it in your resume/portfolio. :-)                 */
    alert("Hello."); 
};

or better yet use something like this (untested!!!):

var addEvent = (function( window, document ) {  
    if ( document.addEventListener ) {  
        return function( elem, type, cb ) {  
            if ( (elem && !elem.length) || elem === window ) {  
                elem.addEventListener(type, cb, false );  
            }  
            else if ( elem && elem.length ) {  
                var len = elem.length;  
                for ( var i = 0; i < len; i++ ) {  
                    addEvent( elem[i], type, cb );  
                }  
            }  
        };  
    }  
    else if ( document.attachEvent ) {  
        return function ( elem, type, cb ) {  
            if ( (elem && !elem.length) || elem === window ) {  
                elem.attachEvent( 'on' + type, function() { return cb.call(elem, window.event) } );  
            }  
            else if ( elem.length ) {  
                var len = elem.length;  
                for ( var i = 0; i < len; i++ ) {  
                    addEvent( elem[i], type, cb );  
                }  
            }  
        };  
    }  
}( this, document ));

// Use like this:
var element = document.getElementById("hello");
addEvent(element, "click", function(){ alert("Hello."); });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.