• .NET Developer Tools DevTools

    UI controls for ASP.NET AJAX, MVC, WPF,
    Silverlight, Windows 8 and Windows Phone

  • Hybrid Mobile Development Icenium

    Cross-platform Mobile Development Tool
    with cloud-based architecture

  • HTML5 / JavaScript Development Kendo UI

    Everything you need to build sites and
    mobile apps with JavaScript and HTML5

  • Testing Tools TestStudio

    One easy tool for Functional, Performance,
    Load and Mobile software testing

  • Web Presence Platform Sitefinity CMS

    Everything for your online business - content
    management, ecommerce, emarketing

  • Agile Project Management TeamPulse

    Simple and intuitive project management
    and collaboration software

Contact us

We are here for you.
  • usa+1‒888‒365‒2779
  • uk+44‒20‒7291‒0580
  • bg+359‒2‒8099850
  • de+49‒89‒2441642‒70
  • au+61‒2‒8090‒1465
  • emailsales@telerik.com
Your account Access to your products, updates and support
Telerik Product Families
  • Your Account
    Your Account
    Log in
  • ABOUT US

    About Telerik

    • Company
    • Press Center
    • Customers
    • Community
    • Careers
    • Contacts
Kendo UI - The way of HTML5
Products ▼
Kendo UI Web Kendo UI Mobile Kendo UI DataViz Server Side Wrappers
Demos Purchase Download
Blogs Documentation
Support ▼
Premium Forums StackOverflow Forums
Resources ▼

Featured Resource

Kendo UI Dojo


Blogs Code Library Demos Documentation FAQ Testing
Premium Forums Roadmap User Voice Videos Webinars More Resources
Contact Us Search
 

Blogs

What You May Not Know About jQuery

Friday, January 06, 2012 by Kendo UI Team Blog | Comments 7

It never ceases to amaze me at how much I don’t know.

jQuery is a pretty straight forward library.  It’s essentially one large object off of which we can call and chain functions.  The beauty of it is in it’s simplicity.  It takes a somewhat convoluted and strange language, and makes it trivial to do really complex things.  That simplicity, though, can give the illusion that you fully understand jQuery from top to bottom. 

Work with the DOM and make AJAX calls right? Pfffft.  I got this.

There’s More?

I was having lunch a while back with Elijah Manor who knows far more about jQuery (and many other things) than I do, and he mentioned the .map() function.  I nodded my head and said to myself, “I have no idea what that is”.  Then I said it out loud because Elijah is a really nice guy and always very helpful.  But it got me to thinking – what else is there that I haven’t seen or don’t know about.

Lots Buddy.  Lots.

Paul Irish did a talk about about 10 performance tips for using jQuery.  Jon Raasch did a summary post that I would highly recommend reading.  One of the things that he talks about at the bottom is some of the lesser known jQuery methods.  And wouldn’t you know it – .map() is the first one in the list.

He doesn’t go into depth on these methods and what they do, so I’m going to pick up where he left off and write some code around these lesser known methods.  Of course, please refer to the official jQuery documentation on all of these which I will link to from each one.  A big thanks to Elijah who gave me input on these methods and helped with some of the ideas expressed here.

.map()

The .map() function takes in an array and operates on each item in the array, returning a new array when it is finished.  Now the first thing that came to my mind is, “Why not just use .each() instead?”  .each() is meant to enumerate over immutable items.  For example, lets say we have a simple array of items.  We want to enumerate over that array and remove an item.  Conventional programming tells you not to do that.  You cannot modify a collection that you are currently in the process of enumerating.  If you try to do this in a static language, it will throw an error telling you the collection has changed.

The idea with .map() is that we can enumerate over the array and modify any or all elements.  This returns a new array.  This is the same thing that you would do if you were trying to modify a collection in a conventional foreach loop.  In the following fiddle, a simple array is modified and the new array contains the new items.  You can see how .map() greatly simplifies traversing and modifying an array.

.slice()

This is another “arrayish” function.  But we already have a slice function in JavaScript arrays – so what is this?  The .slice() function allows you to perform an array like slice on an array of DOM elements.

For instance, in the above example we had an array of items.  Suppose that array of items was an unordered list of items and we wanted to mark the third and fourth items as deleted.  We could use the .slice() to do this.  The first parameter is the index at which to start slicing. The second is where to end. Note that if you pass in a number less than where you started, you will get nothing. If you do not pass in a second parameter you will get the entire list starting at the index provided.

Additionally, since the .slice() method is modeled after the JavaScript slice, you can pass in negative numbers.  This will cause the .slice() method to start at the end of the array and move left by the amount specified in the first parameter.  We could then refactor the above example like so….

.stop()

You are probably familiar with jQuery animations and simple things like .toggle() which toggles an element’s visibility with an animation.  As it turns out, animations are queued, so that if you try to execute an animation on the same object while one is currently in progress, the first one finishes and then the second is executed.  That’s probably not the behavior that you want.  Consider this example.  Suppose we add a toggle button to our list of items to show and hide it.  Watch what happens when you click the “toggle” button before the animation is finished.  Click the button a bunch of times and watch the animation queue, and then fire over and over again.

That's just not at all what we want. We want the current animation to cease before the next one is fired. Currently we have to wait for each animation to finish. I slowed the animation down for added effect.

Using the .stop() method, we can kill the current animation in it’s tracks and start the new one.

There are a couple of parameters that go with .stop() that are probably worth mentioning here.  They are clearQueue and jumpToEnd.  They are both Booleans and are passed in that order.  The defaults are .stop(false,false).

clearQueue clears any animations that are in the queue.  As you saw in the first toggle example, animations can get queued up and this will empty that queue.

jumpToEnd specifies that the current animation should be completed immediately.  In our example using .stop(), the animation is killed in it’s tracks.  This setting says that the animation will complete immediately instead of just stopping altogether.

.prevAll()

This selects all previous same-level elements.  Pretty simple and very useful.  For example, in our list of items, we could attach an event handler to each item and using .prevAll() along with .map() we can return a list of the previous items.

.end()

A lot of people know about this one, but it was new to me and it is super handy.  Have you ever done something like this?

$("div").find("input").val("New Value")
    

What do you get back from that?  Not the div jQuery object, but the input.  This stinks for chaining because if you want to do several things on the div including altering some child elements, you end up doing it on a separate line. The .end() method restores the current object on the chain to it’s previous state. So in the above example, .end()  would in fact give you back the div object.

I should note here that you should probably steer clear of chaining too much.  It’s very useful, but can make code very difficult to maintain.  If you do chain, make sure you drop down on separate lines as I did above so that it’s easier to read.  In the chain indent methods that act on the same object.  you can see from the structure of the code above that find()  and end() are on the same level because they both refer to the div object.  The text() operates on the first li, so it is indented.

Dig In

Maybe not all of these functions are new to you, but it was a learning experience for me.  There are quite a few functions in jQuery that get very little attention because they have a very niche use.  Some of the ones that I wanted to write about, but couldn’t come up with examples for include .queue(), .dequeue(), .delay(), and .pushStack().

As you build with Kendo UI, familiarize yourself with some of the more advanced features of the jQuery library.  They will come in handy when you need them and help reduce the amount of code that you have to write.  It will also make you look really smart when you go to lunch with your friend and they mention .map() and you don’t look back with a blank stare like I did!

About the Author
Burke Holland is a web developer living in Nashville, TN. He enjoys working with and meeting developers who are building mobile apps with jQuery / HTML5 and loves to hack on social API's. Burke works for Telerik as a Developer Evangelist focusing on Kendo UI. Burke is @burkeholland on Twitter.

7 Comments

  1. 1 Steve B 07 Jan 2012
    Great Article Burke.  I wonder if map, slice, and prevAll can be used for sorting items on say a grid ...
  2. 2 Greg Babula 13 Jan 2012
    Great article, I didn't know much about the map() function either so this was very useful 
  3. 3 Tariq 14 Jan 2012
    Nice article Burke Holland
  4. 4 Radoslav Stankov 14 Jan 2012
    I like the article. 

    You could mention that there is also "jQuery.fn.map". Which work similar to "jQuery.map", but returns a jQuery instance wrapping the array.

    Here two example I used recently, that I think will be usefull:

    // get all views count of submissions
    $('.submissions').map(function() { return $(this).data('views'); }).toArray();

    // get all submission author elements
    $('.submissions').map(function() { return $("#user-" + $(this).data('author-id'))[0]; });
  5. 5 Burke 18 Jan 2012
    @radoslav

    That's a great point. It would probably be much more convenient to get the array back wrapped in jQuery then to have to re-wrap to perform some other operation on it.
  6. 6 Jaundalynn 18 Jan 2012
    Good point. I hadn't thought about it quite that way. :)
  7. 7 Tom Legrady 02 Feb 2012
    You mention Paul Irish's talk on JQuery performance tips, and Jon Raasch's  summary post.

    Looking carefully at JOb Raasch's post, I notice it is dated 2009. While much of the document may still be relevant, the second item on Paul's list is a recommendation to use the "new" live() method. But following the link to the JQuery site shows that, far from new, live() is deprecated, and has been for some time. live() is recommended for jQuery 1.3+, delegate() is appropriate for 1.4.3+ and on() for 1.7+.  Internet time does not slow down!

    This highlights the need for a mechanism to track currently valid advice. I have 20 years experience as a programmer, but I'm new to Javascript. I'm eager to learn best practices, but a constantly moving target makes that challenging. Obsolete concepts show up as current at the same time that "recommended blog list" show blogs that have no entries in the past year. Even John Resig's site shows a 6 month old post as 'recent'.

Comment

  1. Click to add

  2. Click to add

  3. Click to add

  4.    
     
    •  
    •  
    •  
    •  
    •  
    •  
    •  
    •  
    •  
    •  
    •  
    •  
     
      
       
Blogs feed
Categories

  • Tutorials (26)
  • Release (33)
  • Browsers (7)
  • Extensions (3)
  • Tip of the Week (10)
  • Videos (5)
  • Concepts and Theory (13)
  • Misc. (25)
  • Framework Constructs (6)
  • Mobile (6)
  • UI Widgets (5)
  • Blogs (1)
Archive
  • 2013 May (7)
  • 2013 April (10)
  • 2013 March (9)
  • 2013 February (12)
  • 2013 January (10)
  • 2012 December (9)
  • 2012 November (11)
  • 2012 October (6)
  • 2012 September (7)
  • 2012 August (8)
  • 2012 July (10)
  • 2012 June (8)
  • 2012 May (10)
  • 2012 April (7)
  • 2012 March (13)
  • 2012 February (10)
  • 2012 January (6)
  • 2011 December (10)
  • 2011 November (4)
  • 2011 October (6)
  • 2011 September (5)
  • 2011 August (9)
Home Web Mobile DataViz Server Wrappers Whitepapers Surveys Chrome Icenium Contact Us

Kendo UI framework is developed by Telerik - a leading provider of UI components for web, desktop and mobile applications. Trusted by over 100,000 customers worldwide for our devotion to quality and industry-best technical support, Telerik helps professionals maximize their productivity and "deliver more than expected" every day.

kendoui - powered by html5, css3 & jquery
get social
  • Twitter
  • Facebook
  • Google plus
  • RSS
Privacy Policy | Branding Guidelines
Powered by Sitefinity CMS

Copyright © 2011 - 2013 Telerik Inc. All rights reserved.