tags:

views:

476

answers:

16

I just had the jQuery epiphany the other day and still feel like there is tons of power in it that I'm not utilizing.

So that said, what is your favorite feature of jQuery that saves you time and/or makes your client side applications that much more cool or powerful?

+8  A: 

Selectors, and chaining.

Seb
+7  A: 

Chaining! Huge jQuery chains are amazing. Sometimes I can't stop. It feels almost like doing everything in one line (you want to, don't deny it).

this.lasso = $('<div/>')
    .css({ position: 'absolute', overflow: 'hidden' })
    .addClass('ui-crop-lasso')
    .hide()
    .appendTo('body')
    .resizable({
        handles: 'all',
        start: setLasso,
        stop: setLasso,
        resize: setLasso,
        minHeight: 50,
        minWidth: 50
    })
    .draggable({
        containment: el,
        cursorAt: 'move',
        drag: setLasso
    });

Try it out, you'll be addicted in no time.

brad
By no means whatsoever is HUGE code amazing.
Seb
Huge code? That's a single line of JQuery taht makes something resizable, draggable, gives it a class and hard coded styles and inserts it in the DOM. While this may not always be the best approach, it is incredibly versatile.
Soviut
@Seb the thing about jQuery chaining is that it is readable and straight-forward (when used correctly).
jskulski
@Seb Yea, but I didn't say "Huge code is amazing", I said "Huge jQuery chains are amazing". Chaining often reduces the overall size of my code since I don't need to repeat variable names over and over. For example: "$('#foo').find('.bar').hide();" is much shorter than "var foo = $('#foo'); var bar = foo.find('.bar'); bar.hide();"
brad
+3  A: 

The way jQuery objects works regardless of being none, one or many DOM elements in it.

Also, event handling rocks. Being able to just return false on click events, for example, rocks.

August Lilleaas
the "return false" thing is a vanilla javascript feature too, you know. try this: <a href="somepage.html" onclick="return false">..</a>
nickf
+1, I think you mean to say 'implicit iteration' in your first point, which you are the only person to have pointed out. My favourite feature by far.
karim79
@nickf: when hooking events solely with javascript, though, it's not that easy. Take a look at how e.g. prototype does it, you gotta pass false as an argument or something like that.
August Lilleaas
+6  A: 

The plugin system is incredible. You technically could be, and remain, a complete JQuery novice and still exploit most, if not all, of its power via the application of plugins. This makes it very popular with artists and non-programmers just looking to add a tooltip, modal dialog, lightbox, drop down menu, etc.

Soviut
Just like a new Ferrari. It lets you go incredibly fast, right until you smash into a wall at 140mph because you don't know how to turn
Mike Robinson
I agree, but that can be the case with any language or tool though. I've found it most useful for the novice who "just wants a lightbox" and doesn't want to have to learn a lot of javascript to implement it. JQuery has a huge appeal to the non-programmers and artists for this exact reason.
Soviut
I also find it pretty pithy that my answer has been downvoted twice. Just because plugins may give the amateur coder enough rope to hang themselves with, it gives the seasoned veteran a very powerful toolkit.
Soviut
A: 

Not exactly a feature but the amount of already written plug-ins and community information on how to use jQuery is definitely a bonus. Otherwise, selectors along with the plug-in system.

rball
+24  A: 

My favorite feature of jQuery is how it helped to turned JavaScript from a hated language into a sexy language almost overnight.

Erik Forbes
exactly what i came into say
jskulski
Well... actually... that's not a feature, but I agree that's great.
Seb
And I still hate JavaScript anyway.
Damien
I call bullshit. It wasn't the library that changed that... It was prototype. And No I am not a prototype fan boy as I use jQuery - I just believe that John Resig get's all the credit that some other developers deserve too.
Dmitri Farkov
@Dmitri what about dojo? Mootools? :) jQuery really was the library that exploded into the mainstream, at least from what I can tell.
TM
Okay, there ya go.
Erik Forbes
Yep, the fact that it makes JavaScript programming (actually, DOM programming) fun, whereas DOM programming still is the same PITA/annoyance it's always been.
Wim Leers
+2  A: 

As a newcomer to jQuery, it has to be the jQuery UI plugin, and the themes people have designed to go with it. ThemeRoller lets you quickly adapt themes and play "what if" scenarios with your application as it's being displayed in Firefox. I was able to hugely improve a web application through the use of tabs, accordion sliders, datepickers, and alerts in just a day or two starting from no knowledge of jQuery at all.

More experienced web developers will like jQuery's philosophy of "unobtrusive JavaScript", its rigorous leveraging of XHTML and CSS, selectors, and chaining.

Jim Ferrans
+15  A: 

Creating an HTML Element and keeping a reference:

var newDiv = $('<div></div>');
newDiv.attr("id","myNewDiv").appendTo("body");
//Now whenever I want to append the new div I created, 
//I can just reference it from the 'newDiv' variable

Checking if an element exists:

if ($("#someDiv").length) {
    //it exists...
}

Writing your own selectors:

$.extend($.expr[':'], {
    over100pixels: function(a) {
        return $(a).height() > 100;
    }
});

$('.box:over100pixels').click(function() {
    alert('The element you clicked is over 100 pixels high');
});
Andreas Grech
write your own selectors? That's pretty neat.
Andrew
+12  A: 

Not having to worry (as much) about compatibility among different browsers

SeanDowney
A: 

I like the fact that it treats novices and experts alike equally, to a certain degree. If you know what you are doing, though, you can really make an application shine in all respects. Things such as lazy loading, code separation and templating can all be accomplished with jQuery. It was designed as a DOM tool, but can be easily adapted to be namespaced and to act as a full-stack js framework.

In a nutshell, I think the best feature of jQuery is that it was designed from all angles with the idea of simplicity in mind. The simplest answer is usually the best answer.

Tres
+2  A: 

Mostly things which require lot of cross-browser testing and tweaking which I could not possibly write myself as reliable and test so extensively as the jQuery community does. This includes:

  • $(document).ready(...). Look at the implementation of this function. There are lot of if-else statements checking various browser features.

  • Position and dimension methods: $(...).offset(), $(...).position(), $(...).width(), $(...).innerWidth() etc. Again, the same story here. Also, they work reliably (or I assume more reliably that I would be able to achieve myself) for special cases such as window and document.

  • $(...).animate(). The ability to animate elements based on any (reasonable) CSS style. Also animation chaining and $(...).stop(). Very fluent API.

  • Event handlers. This is something that every JavaScript library has, and it’s not anything one could not implement himself, but it’s nice to have.

There are also some less favourite features. One of them is function chaining which seems to be the semi-official jQuery programming style. It may impressive at the first sight, but overall, it’s not anything you cannot do using variables and separate statements and in the end, in my opinion, it leads to a less readable code.

Another minor thing which I like less is eagerness of using closures and deeply nested anonymous functions. It may be harder to read such code after a week. It may not immediately obvious where some variables are coming from and what function scopes are. Try to ready some more elaborate jQuery source to see what I mean.

Even though, one of the selling points of jQuery is selectors, I find that I don't need them so often, and if I need any, I usually get by with the basic ones.

Finally, jQuery DOM manipulation has some useful utilities, but overall, I think one could achieve the same with a little bit more (albeit tedious) code. I know I'm most likely oversimplifying, but it does not seem like that there are some serious cross-browser issues.

Jan Zich
with use of appropriate indentation, I find that the chained statement style of coding can be even more readable than regular code.
nickf
+1  A: 

Selectors with support for CSS 1-3 and XPath combined and your own custom selectors!

// "odd" numbered rows in a table with class "orders"
jQuery('table.orders tr:odd')

// All external links (links that start with http://)
jQuery('a[@href^="http://"]')
aleemb
that second example became deprecated (or dropped altogether?) since version 1.2. jQuery('a[href^="http://"]') is the correct way now (CSS style, rather than XPath).
nickf
+4  A: 

I like jQuery's aspect of removing event handlers from HTML to separate content from behavior. Instead of writing

<p class="active" onclick="myFunction()">foo</p>

numerous times on a web page, I can write this instead:

<p class="active">foo</p>

and write this once inside my script tags:

$(".active").click(function(){ ... });

Why do I like this better? Because jQuery separates content from functionality the same way that CSS separates content from style. And as Jan Zich and others mention, jQuery makes a lot of that functionality very easy to program for any browser, so for example animation becomes a breeze when you want to simulate tabs that display/hide divs on a page for the user.

Paul
+2  A: 

Regex in the selectors (since I use ASP.Net and the controls have ridiculous, rendered IDs.)

To get this in jQuery:

<asp:TextBox ID="txtTest" runat="server" />

I just do this:

$("input[id$='txtTest']")

It has made me change my outlook on doing client side stuff on web sites.

Gromer
I am constantly baffled by you ASP.Net guys and your generated html.
nickf
It's the only way the engine can deal with nested controls and whatnot. I suppose it could check everything used in the page to verify uniqueness dev time, but it would take a good deal of CPU to do that.
Gromer
But either way, I do hate the generated markup from ASP.Net. A lot.
Gromer
It's best to use '_txtTest'. If you have controls named 'Name', FirstName', 'CompanyName', and you go and do $("input[id$=Name]") you'll get all of them
Mark
@Mark, it won't be an issue if you put the whole ID in it. If there was a txtTest in a control on the page, the compiler wouldn't catch it and thus two controls would end with txtTest though.
Gromer
The point of using the "$=" (ends with) is to skip the ASP.Net naming container prefix. I don't want to know the ClientID, but I also don't want to mistakenly find a control that ends with same name as another control.
Mark
No no, I'm saying put in the whole ID that you put in your markup, so in my example above, txtTest. From your comment, I took it as you have 3 controls on the page, txtFirstName, txtLastName and txtCompanyName. You only searched for Name, as opposed to txtFirstName if you wanted the first name field, etc...
Gromer
@Gromer Ahh..no. I typically don't prefix my control names, but rather suffix them. So instead of txtTest, I would use TestTextBox, or FirstNameTextBox. I can see where the prefix "txt" is serving the same purpose as including the last part of the naming container "_".
Mark
So, what we've learned is ASP.Net generated IDs are a pain!
Gromer
+1  A: 

Plug-in system:

((function($){
    $.fn.plugin = function(){
        return this.each(function(){
            //code here
        });
    }
})(jQuery)

Chaining:

$('.parent').children().remove().end().css('background-color', 'red');

Cross-browser compatibility across variety of features, eg. Ajax

$.GET('url', {data: 'here'}, function(data){ /* callback */ });
Dmitri Farkov
+1  A: 

Relative values in the animate funciton:

$('div.class:hover').animate({ height: '+=10', width: '+=10', opacity: '-=.5' })