211

I am starting a project with jQuery.

What pitfalls/errors/misconceptions/abuses/misuses did you have in your jQuery project?

casperOne
  • 73,706
  • 19
  • 184
  • 253
flybywire
  • 261,858
  • 191
  • 397
  • 503
  • 4
    This should *not* have been closed for being "not constructive". Some very helpful answers have materialized and the question has been starred 220 times now. Please vote to reopen, if you have sufficient karma. – Roy Prins Jan 04 '15 at 08:52
  • Seems to me, jQuery is a pitfall in itself – birgersp Aug 06 '15 at 08:10

27 Answers27

189

Being unaware of the performance hit and overusing selectors instead of assigning them to local variables. For example:-

$('#button').click(function() {
    $('#label').method();
    $('#label').method2();
    $('#label').css('background-color', 'red');
});

Rather than:-

$('#button').click(function() {
    var $label = $('#label');
    $label.method();
    $label.method2();
    $label.css('background-color', 'red');
});

Or even better with chaining:-

$('#button').click(function() {
    $("#label").method().method2().css("background-color", "red"); 
});

I found this the enlightening moment when I realized how the call stacks work.

Edit: incorporated suggestions in comments.

Gavin Gilmour
  • 6,833
  • 4
  • 40
  • 44
91

Understand how to use context. Normally, a jQuery selector will search the whole doc:

// This will search whole doc for elements with class myClass
$('.myClass');

But you can speed things up by searching within a context:

var ct = $('#myContainer');
// This will search for elements with class myClass within the myContainer child elements
$('.myClass', ct);
slolife
  • 19,520
  • 20
  • 78
  • 121
  • 9
    Aaaaaaah! Well, that's about 1,000,000 of my bugs fixed. +1 – jammus Aug 06 '09 at 14:53
  • 4
    It seems your last point is incorrect - http://groups.google.co.uk/group/jquery-dev/browse_thread/thread/b8c414b373163895 – James Aug 14 '09 at 12:28
  • 1
    Thanks for pointing this out JP. Now, what to do... Should I delete my answer so no one else goes hog wild and changes their code for nothing? – slolife Aug 14 '09 at 16:47
  • Nah, it's still a good point, optimization-wise. :) – James Aug 14 '09 at 21:03
  • 2
    jQuery checks to see if the context is an instace of jQuery so there is no reason for `[0]`. `$('.myClass', ct);` or if you know ct is an instance of jQuery you can use find `ct.find(".myClass")` – gradbot May 14 '11 at 21:04
  • I created a jsperf test to illustrate this point, the results of which will change how I select with jQuery. Check it out at http://jsperf.com/jquery-context-or-no-context – Zander Jun 11 '12 at 14:51
63

Don't use bare class selectors, like this:

$('.button').click(function() { /* do something */ });

This will end up looking at every single element to see if it has a class of "button".

Instead, you can help it out, like:

$('span.button').click(function() { /* do something */ });
$('#userform .button').click(function() { /* do something */ });

I learned this last year from Rebecca Murphy's blog

Update - This answer was given over 2 years ago and is not correct for the current version of jQuery. One of the comments includes a test to prove this. There is also an updated version of the test that includes the version of jQuery at the time of this answer.

BrianH
  • 7,932
  • 10
  • 50
  • 71
  • This makes all the sense in the world to me but I could of swore that it was the otherway around for some reason. I thought people were saying that it is a bad idea to help" it which made no sense to me so glad to see this is correct – JasonDavis Aug 25 '09 at 21:07
  • 6
    I was also under the impression that the reverse was true. Perhaps this is the case in browsers that don't implement getElementsByClassName, but otherwise you are just giving jQuery more work to do. I would very much like to see Rebecca post some benchmarks :) – Alex Barrett Oct 02 '09 at 17:40
  • 7
    You're REDUCING the amount of work it has to do. It's like telling somebody to get your socks out of the drawer in your dresser instead of telling them to get the socks out of your room. Reduces the amount of 'looking' it has to do substantially. – Sneakyness Dec 31 '09 at 07:52
  • 4
    The reverse is true when you are writing CSS (at least including the element tag). See http://code.google.com/speed/page-speed/docs/rendering.html#UseEfficientCSSSelectors – kmiyashiro Feb 04 '11 at 23:13
  • 7
    @Sneakyness Not everything has an accurate analogue of real life. For example, `$('.b')` could use `document.getElementsByClassName('b')` if the browser supports it, but doing `$('a.b')` will cause it to get all matching elements with class `b` and then confirm they are anchors in a two stage operation. The latter sounds like more work to me. For a real life analogy, try this: *Find all socks in my room. Now, throw out ones which are not in my dresser.* – alex Mar 18 '11 at 07:03
  • ...Though I suspect it may be faster to use both when using `document.querySelectorAll()`. According to my benchmark using Chrome 10, [not giving the element is faster](http://jsperf.com/specififty-with-jquery-selectors). – alex Mar 18 '11 at 07:09
  • @alex: Shouldn't it have something to do with QSA? It should be performantly similar... but benchmarks are benchmarks... – BoltClock Mar 18 '11 at 07:23
  • @BoltClock Well QSA should be able to optimise it much more easily. – alex Mar 18 '11 at 07:27
  • 2
    I believe the misconception on selectors is due to the fact that in older versions of jquery, it was faster to do $('#foo') rather than $('div#foo'), since by definition, an id is unique. I'm pretty sure this was fixed in later releases however, but that recommendation applied only to ids, not other types of selectors – Alex Heyd Mar 18 '11 at 19:54
  • @alex It definitely makes sense for `id` selectors, however, if you have jQuery that is ran on every page, sometimes (though rarely) you do need to differentiate between `li#a` and `#a`. – alex Mar 19 '11 at 01:38
  • 2
    Disappointing that such a flat out wrong answer is offered as second best. Sizzle works from right to left; it will first get all `.button` elements, then check if they have a `span` parent. That's a fair bit slower than simply searching for `.button`. (Selectors starting with an id are exceptions, in that Sizzle will process the id first, but that still does not necessarily make things faster - see [test](http://jsperf.com/sizzle-id-specificity).) – Tgr Jul 02 '11 at 10:49
36

Try to split out anonymous functions so you can reuse them.

//Avoid
$('#div').click( function(){
   //do something
});

//Do do
function divClickFn (){
   //do something    
}

$('#div').click( divClickFn );
redsquare
  • 78,161
  • 20
  • 151
  • 159
  • 20
    I think this applies to roughly the same degree that synchronous (inline) code should be broken up into named functions. If you've got a chunk of code that is begging to be given a name, then go for it. But don't move the code out of line simply because you're wrapping it inside a function; anonymous functions exist for good reason. – Dan Breslau Aug 04 '09 at 19:23
  • 4
    Actually I like to give 'name' to my function. It is very useful when you are debugging the code and instead of seeing an endless list of anonymous functions, you see properly named functions. – SolutionYogi Aug 04 '09 at 19:47
  • 1
    Your point is well taken, and I've probably been tripped by this myself a few times. Even so, "*roughly* the same degree" still works for me. – Dan Breslau Aug 04 '09 at 20:48
  • 1
    esp. if the binding is happening in a loop! – SavoryBytes Aug 07 '09 at 18:17
  • Named functions also benefit you greatly when debugging; nothing sucks more than looking at a callstack 8 levels deep that has nothing but `(anonymous)`. Read more on this tip here: http://stackoverflow.com/questions/182630/jquery-tips-and-tricks/696385#696385 – ken Dec 29 '10 at 21:39
  • If you put a function definition in a loop you will take a performance hit since it will create a new function with each iteration. – gradbot May 14 '11 at 21:06
  • I think this is mainly important if you find yourself simulating events, like `$play.click();` because you defined your functionality in an event handler. Then you should definitely have the functionality in a seperate function. – 1j01 Feb 02 '15 at 20:20
  • How can I access the clicked div within `divClickFn` ? in the closure I can do `$(this)` , but in the function it returns `window` instead of `#div` – stilllife Feb 07 '16 at 11:39
34

While using $.ajax function for Ajax requests to server, you should avoid using the complete event to process response data. It will fire whether the request was successful or not.

Rather than complete, use success.

See Ajax Events in the docs.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Artem Barger
  • 40,769
  • 9
  • 59
  • 81
  • 1
    I've been back and forth on success vs complete, can you expand on why you think complete is better? – Neil N Aug 04 '09 at 19:00
  • 1
    I'm not saying complete is better. What I was trying to say is that you need to avoid misleading use of complete and should use success in order to be able to process the response data. – Artem Barger Aug 04 '09 at 19:03
  • 2
    Well it always gets called. However I would disagree. Complete is best for hiding a loading gif etc. You should use the success for handling the response and the error for any errors of course. – redsquare Aug 04 '09 at 19:03
  • 1
    He is suggesting to use success instead of complete. 'complete' always fires when the ajax request is 'complete', doesn't matter it completed successfully or unsuccessfully. – SolutionYogi Aug 04 '09 at 19:04
  • @redsquare, can you expand on that exactly you disagree with? I was referring to data process and didn't mind any pictures hiding/showing opportunities you have with complete handler . – Artem Barger Aug 04 '09 at 19:07
  • Like Neil N I got the wrong tone of the answer – redsquare Aug 04 '09 at 19:11
  • Ok, I see. I've putted the mark to get it more understandable. – Artem Barger Aug 04 '09 at 19:14
  • -1 so? maybe are scenarios where you need it .use it only if you know how it works. – Elzo Valugi Aug 06 '09 at 11:06
  • I just tried to say that people frequently confuses between those two, so just tried to warn that it has different semantic notation. So if you going this way you should downvote all answers here, since all of them is not helpful much once you know how things in jquery works. – Artem Barger Aug 06 '09 at 15:25
34
  • Avoid abusing document ready.
  • Keep the document ready for initialize code only.
  • Always extract functions outside of the doc ready so they can be reused.

I have seen hundreds of lines of code inside the doc ready statement. Ugly, unreadable and impossible to maintain.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
redsquare
  • 78,161
  • 20
  • 151
  • 159
  • 6
    +1. In general, most of the jQuery code I have seen uses functions with hundreds of lines. I don't know why 'jQuery developers' don't like to use smaller functions. – SolutionYogi Aug 04 '09 at 19:28
  • 6
    @SolutionYogi because most are just JS noobs? – adamJLev Jun 16 '10 at 05:14
  • I'm all for not putting very long functions in document ready, that's good advice. However, making many small component functions that are run from an overarching function that isn't in document ready isn't necessarily the best practice. If the overarching function is the only one that uses those pieces of code you're better off putting it all in the one function even if it's harder to read. Calling functions has a lot of overhead and if you're only using the code in one context it should be avoided. – sage88 Sep 20 '13 at 16:42
24

If you bind() the same event multiple times it will fire multiple times . I usually always go unbind('click').bind('click') just to be safe

jball
  • 24,791
  • 9
  • 70
  • 92
Scott Evernden
  • 39,136
  • 15
  • 78
  • 84
24

"Chaining" Animation-events with Callbacks.

Suppose you wanted to animate a paragraph vanishing upon clicking it. You also wanted to remove the element from the DOM afterwards. You may think you can simply chain the methods:

$("p").click(function(e) {
  $(this).fadeOut("slow").remove();
});

In this example, .remove() will be called before .fadeOut() has completed, destroying your gradual-fading effect, and simply making the element vanish instantly. Instead, when you want to fire a command only upon finishing the previous, use the callback's:

$("p").click(function(e){
  $(this).fadeOut("slow", function(){
    $(this).remove();
  });
});

The second parameter of .fadeOut() is an anonymous function that will run once the .fadeOut() animation has completed. This makes for a gradual fading, and a subsequent removal of the element.

Community
  • 1
  • 1
Sampson
  • 265,109
  • 74
  • 539
  • 565
23

Don't abuse plug-ins.

Most of the times you'll only need the library and maybe the user interface. If you keep it simple your code will be maintainable in the long run. Not all plug-ins are supported and maintained, actually most are not. If you can mimic the functionality using core elements I strongly recommend it.

Plug-ins are easy to insert in your code, save you some time, but when you'll need an extra something, it is a bad idea to modify them, as you lose the possible updates. The time you save at the start you'll loose later on changing deprecated plug-ins.

Choose the plug-ins you use wisely. Apart from library and user interface, I constantly use $.cookie , $.form, $.validate and thickbox. For the rest I mostly develop my own plug-ins.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Elzo Valugi
  • 27,240
  • 15
  • 95
  • 114
  • 2
    What about grid? You make your own? – jmav Oct 28 '09 at 00:04
  • yes. from project to project data comes in various ways. I prefer to have full control that realizing that grid only helps me to the middle and then I have to improvise. – Elzo Valugi Oct 28 '09 at 08:49
  • IF{ given enough time, generally i prefer to write all data-driven-dom-manipulation (css/html) code directly. in other words - do not pass data to a 'plugin' and have it spew html. its hard enough to evaluate (the midfield of) plugins for current scope compatibility, forget about the future demands. think... designers, planners, managers, managers, managers. oh and clients and users. but if you have all those things, you will not have enough of said 'time'. so just go use jqgrid already - youre wasting time deliberating. is it done yet?} – user406905 Dec 18 '10 at 04:33
22

Pitfall: Using loops instead of selectors.

If you find yourself reaching for the jQuery '.each' method to iterate over DOM elements, ask yourself if can use a selector to get the elements instead.

More information on jQuery selectors:
http://docs.jquery.com/Selectors

Pitfall: NOT using a tool like Firebug

Firebug was practically made for this kind of debugging. If you're going to be mucking about in the DOM with Javascript, you need a good tool like Firebug to give you visibility.

More information on Firebug: http://getfirebug.com/

Other great ideas are in this episode of the Polymorphic Podcast: (jQuery Secrets with Dave Ward) http://polymorphicpodcast.com/shows/jquery/

Dan Esparza
  • 28,047
  • 29
  • 99
  • 127
14

Misunderstanding of using this identifier in the right context. For instance:

$( "#first_element").click( function( event)
{
   $(this).method( ); //referring to first_element
   $(".listOfElements").each( function()
   {
      $(this).someMethod( ); // here 'this' is not referring first_element anymore.
   })
});

And here one of the samples how you can solve it:

$( "#first_element").click( function( event)
{
   $(this).method( ); //referring to first_element
   var $that = this;
   $(".listOfElements").each( function()
   {
      $that.someMethod( ); // here 'that' is referring to first_element still.
   })
});
Javier Constanzo
  • 443
  • 1
  • 4
  • 16
Artem Barger
  • 40,769
  • 9
  • 59
  • 81
13

Avoid searching through the entire DOM several times. This is something that really can delay your script.

Bad:

$(".aclass").this();
$(".aclass").that();
...

Good:

$(".aclass").this().that();

Bad:

$("#form .text").this();
$("#form .int").that();
$("#form .choice").method();

Good:

$("#form")
    .find(".text").this().end()
    .find(".int").that().end()
    .find(".choice").method();
googletorp
  • 33,075
  • 15
  • 67
  • 82
  • 2
    $(".aclass").this().that(); is not good! class only selectors are slow – redsquare Aug 04 '09 at 21:24
  • It's an illustrative example showing Jquery's ability to use several methods on one selection. I made the selection simple (and thus slow) to give greater focus on this technique. – googletorp Aug 05 '09 at 00:20
  • 11
    While avoiding searching the DOM repeatedly is a good thing — the last example is an unreadable mess where I've got no idea what is going on. If you plan to use the result of a fetch multiple times, store it in a variable. It makes code much more maintainable. – Quentin Aug 05 '09 at 11:44
12

Always cache $(this) to a meaningful variable especially in a .each()

Like this

$(selector).each(function () {
    var eachOf_X_loop = $(this); 
})
David Wolever
  • 148,955
  • 89
  • 346
  • 502
adardesign
  • 33,973
  • 15
  • 62
  • 84
10

Similar to what Repo Man said, but not quite.

When developing ASP.NET winforms, I often do

$('<%= Label1.ClientID %>');

forgetting the # sign. The correct form is

$('#<%= Label1.ClientID %>');
Ron
  • 1,786
  • 19
  • 20
10

Events

$("selector").html($("another-selector").html());

doesn't clone any of the events - you have to rebind them all.

As per JP's comment - clone() does rebind the events if you pass true.

Chris S
  • 64,770
  • 52
  • 221
  • 239
9

Avoid multiple creation of the same jQuery objects

//Avoid
function someFunc(){
   $(this).fadeIn();
   $(this).fadeIn();
}

//Cache the obj
function someFunc(){
   var $this = $(this).fadeIn();
   $this.fadeIn();
}
cllpse
  • 21,396
  • 37
  • 131
  • 170
redsquare
  • 78,161
  • 20
  • 151
  • 159
  • var $this = $(this).fadeIn();? you're caching an effect? – Jason Aug 04 '09 at 20:41
  • 12
    it returns the element, Its called chaining! – redsquare Aug 04 '09 at 20:55
  • you can set a variable and perform an action on it at the same time? – Jason Aug 04 '09 at 23:00
  • 1
    Indeed, but dont take my word for it. Try it. How do you think the following is possible if the jquery object representing the element is not returned? $('#divId').hide().show().fadeIn()....etc – redsquare Aug 04 '09 at 23:07
  • 14
    That works, but I think it's more readable to have `$this = $(this);` on a separate line. If you can (without making a mess), forget about `$this` and just chain everything: `$(this).fadeIn().fadeIn();` – Patrick McElhaney Aug 05 '09 at 14:40
  • Why when then works just fine. Your just making extra lines for no reason. It is still just as readable. Typically when doing an animation you will use the callback so a cached var is needed. – redsquare Aug 05 '09 at 14:56
  • The reason why is because it's more idiomatic. – cdmckay Nov 11 '09 at 20:10
  • you are also effectively calling $(this).fadeIn().fadeIn(); every time you call someFunc() – scottm Nov 11 '09 at 20:17
  • yes yes it was just an example.....not meant for use, was to show the caching! – redsquare Nov 11 '09 at 20:39
8

I say this for JavaScript as well, but jQuery, JavaScript should NEVER replace CSS.

Also, make sure the site is usable for someone with JavaScript turned off (not as relevant today as back in the day, but always nice to have a fully usable site).

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Martin
  • 11,031
  • 8
  • 50
  • 77
6

Making too many DOM manipulations. While the .html(), .append(), .prepend(), etc. methods are great, due to the way browsers render and re-render pages, using them too often will cause slowdowns. It's often better to create the html as a string, and to include it into the DOM once, rather than changing the DOM multiple times.

Instead of:

var $parent = $('#parent');
var iterations = 10;

for (var i = 0; i < iterations; i++){
    var $div = $('<div class="foo-' + i + '" />');
    $parent.append($div);
}

Try this:

var $parent = $('#parent');
var iterations = 10;
var html = '';

for (var i = 0; i < iterations; i++){
    html += '<div class="foo-' + i + '"></div>';
}

$parent.append(html);

Or even this ($wrapper is a newly created element that hasn't been injected to the DOM yet. Appending nodes to this wrapper div does not cause slowdowns, and at the end we append $wrapper to $parent, using only one DOM manipulation):

var $parent = $('#parent');
var $wrapper = $('<div class="wrapper" />');
var iterations = 10;

for (var i = 0; i < iterations; i++){
    var $div = $('<div class="foo-' + i + '" />');
    $wrapper.append($div);
}

$parent.append($wrapper);
Alex Heyd
  • 1,323
  • 1
  • 10
  • 17
  • +1... I'm using .html() on multiple elements every second. Noticed it does start to slow everything down! – User2 Jun 26 '14 at 09:16
5

Using ClientID to get the "real" id of the control in ASP.NET projects.

jQuery('#<%=myLabel.ClientID%>');

Also, if you are using jQuery inside SharePoint you must call jQuery.noConflict().

Jacobs Data Solutions
  • 4,850
  • 4
  • 33
  • 38
4

Passing IDs instead of jQuery objects to functions:

myFunc = function(id) { // wrong!
    var selector = $("#" + id);
    selector.doStuff();
}

myFunc("someId");

Passing a wrapped set is far more flexible:

myFunc = function(elements) {
    elements.doStuff();
}

myFunc($("#someId")); // or myFunc($(".someClass")); etc.
Craig Stuntz
  • 125,891
  • 12
  • 252
  • 273
3

Excessive use of chaining.

See this:

this.buttonNext[n ? 'bind' : 'unbind'](this.options.buttonNextEvent, this.funcNext)[n ? 'removeClass' : 'addClass'](this.className('jcarousel-next-disabled')).attr('disabled', n ? false : true);

Explanation

Community
  • 1
  • 1
SolutionYogi
  • 31,807
  • 12
  • 70
  • 78
  • 1
    It looks funny, it's a sort of obfuscation. – Dykam Aug 04 '09 at 19:06
  • 6
    Chaining (on it's own) is difficult to use 'in excess'. It looks like that code makes excessive use of the javascript ternary operator. See http://en.wikipedia.org/wiki/Ternary_operation#JavaScript for more information. – Dan Esparza Aug 04 '09 at 19:43
  • 3
    I'm glad I don't have to maintain your code. – cdmckay Nov 11 '09 at 20:14
3

Use strings accumulator-style

Using + operator a new string is created in memory and the concatenated value is assigned to it. Only after this the result is assigned to a variable. To avoid the intermediate variable for concatenation result, you can directly assign the result using += operator. Slow:

a += 'x' + 'y';

Faster:

a += 'x';
a += 'y';

Primitive operations can be faster than function calls

Consider using alternative primitive operation over function calls in performance critical loops and functions. Slow:

var min = Math.min(a, b);
arr.push(val);

Faster:

var min = a < b ? a : b;
arr[arr.length] = val;

Read More at JavaScript Performance Best Practices

Pir Abdul
  • 2,274
  • 1
  • 26
  • 35
1

If you want users to see html entities in their browser, use 'html' instead of 'text' to inject a Unicode string, like:

$('p').html("Your Unicode string")
1

my two cents)

Usually, working with jquery means you don't have to worry about DOM elements actual all the time. You can write something like this - $('div.mine').addClass('someClass').bind('click', function(){alert('lalala')}) - and this code will execute without throwing any errors.

In some cases this is useful, in some cases - not at all, but it is a fact that jquery tends to be, well, empty-matches-friendly. Yet, replaceWith will throw an error if one tries to use it with an element which doesn't belong to the document. I find it rather counter-intuitive.

Another pitfall is, in my opinion, the order of nodes returned by prevAll() method - $('<div><span class="A"/><span class="B"/><span class="C"/><span class="D"/></div>').find('span:last-child').prevAll(). Not a big deal, actually, but we should keep in mind this fact.

shabunc
  • 23,119
  • 19
  • 77
  • 102
0

If you plan to Ajax in lots of data, like say, 1500 rows of a table with 20 columns, then don't even think of using jQuery to insert that data into your HTML. Use plain JavaScript. jQuery will be too slow on slower machines.

Also, half the time jQuery will do things that will cause it to be slower, like trying to parse script tags in the incoming HTML, and deal with browser quirks. If you want fast insertion speed, stick with plain JavaScript.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
mkoryak
  • 57,086
  • 61
  • 201
  • 257
  • 1
    -1 The _.html()_ function is just as fast as the native approach – cllpse Sep 14 '09 at 16:15
  • everyone who is downvoting me obviously hasnt tried inserting a ton of DOM on IE and watch things become slow. Reason jquery is slow is it will not simply insert the dom, it does a few other things, like check if the dom has scripts, and executes them if its in IE, and some other stuff that you dont need to do if you know exactly what kind of data you are inserting – mkoryak Mar 01 '10 at 16:25
  • 1
    As long as you don't need to worry about browser leaks and such, `.innerHTML` will do. But if you're building something like Gmail where the user keeps the tab open for hours, you're just going to have to bite the bullet and deal with the extra slowness. For the curious, here's exactly what jQuery's `.html()` does: http://james.padolsey.com/jquery/#v=1.4&fn=jQuery.fn.html – adamJLev Jun 16 '10 at 05:30
-1

Using jQuery in a small project that can be completed with just a couple of lines of ordinary JavaScript.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
vise
  • 12,713
  • 11
  • 52
  • 64
  • I don't mind being modded down, but please argument your choice. – vise Aug 31 '09 at 21:07
  • 8
    -1 jQuery abstracts a broken API. This way you are always sure your code is working. Say you've written some code using jQuery and some random browser-bug gets introduced with a new version--all you need to do is import an updated version of the jQuery framework. Versus having to figure out how to solve the bug yourself. – cllpse Sep 14 '09 at 16:17
  • +1 seems reasonable to me - if you're using just a few lines, make sense to just use vanilla JS. – alex Sep 14 '09 at 23:41
  • 1
    @roosteronacid, your argument misses the point. It's very unlikely for a browser to introduce a regression in a script of lesser complexity, or dealing with crossbrowser issues for that matter. Two years ago I've working with mootools and under a certain circumstance it was unable to read an elements content on IE. After a few hours of tring to figure out the problem I just rewrote that part with plain js. So, it's actually more likely for jQuery to break rather than plain javascript to fail due to a browser upgrade. I'd solve a bug my self any day rather than hacking through a libraries code. – vise Sep 15 '09 at 00:15
  • 3
    `couple of lines of ordinary JavaScript` Sure no problem. But when is it ever just that? People that say "why not use vanilla javascript??" haven't been bitten hard enough by IE yet... and not to mention how much cruft and boilerplate code you have to write to do simple things in plain old JS. – adamJLev Jun 16 '10 at 05:23
  • @vise I'm surprised you found a bug in MooTools. After 3 years working on mainly JS, I have yet to find a bug in either MooTools or jQuery. I think one of the tens of thousands of users of the framework would notice a bug and open a ticket or submit a bugfix before you can finish typing `alert()` ;-) – adamJLev Jun 16 '10 at 05:26
  • dom manipulation with jQuery produces much, much cleaner and simpler code than "vanilla JavaScript." To say that you shouldn't use it for small projects implies that 80K of (likely cached) bandwidth is more valuable than my time. It's not. – Adam Rackis Feb 06 '12 at 20:04
  • This is the last reply to my own post. A few lines of ordinary javascript means what it means - on those rare occasions that you code something simple (eg. a landing page) that can be achieved with only a few lines of javascript (say 5 or 10) there's no point of including an entire library. Might as well include enctype multipart on all forms while you're at it. – vise Feb 08 '12 at 14:53
-3

Not understanding event binding. JavaScript and jQuery work differently.

By popular demand, an example:

In jQuery:

$("#someLink").click(function(){//do something});

Without jQuery:

<a id="someLink" href="page.html" onClick="SomeClickFunction(this)">Link</a>
<script type="text/javascript">
SomeClickFunction(item){
    //do something
}
</script>

Basically the hooks required for JavaScript are no longer necessary. I.e. use inline markup (onClick, etc) because you can simply use the ID's and classes that a developer would normally leverage for CSS purposes.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jason
  • 51,583
  • 38
  • 133
  • 185