8 jQuery Methods You Need to Know

8 jQuery Methods You Need to Know


8 jQuery Methods You Need to Know

Introduction

jQuery has become the most famous Javascript framework because of its simplicity and totally rewrote the hassle of writing traditional javascript. Well, I used to hate javascript, but jQuery changed my mind. It saves tremendous of time to develop interactive front end interface.

I reckon jQuery documentation contributes to the success of jQuery as well. It's really helpful and concise. I went through the documentation again, and found out some interesting methods that we might have missed. Some of them are pretty common (good to mention anyway), but some of them are not. So, check out the list, if I missed something, drop a comment and shout it out. Enjoy :)

Advertisement

1 .data()

jQuery.com - "The .data() method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks."

With the introduction of HTML5, we can use it as attribute as well. For example

<div data-type="page" data-hidden="true" data-options='{"name":"John"}'></div>

//We can call it via:
$("div").data("role") === "page";
$("div").data("hidden") === true;
$("div").data("options").name === "John";

The following will work as the above example too:

$("div").data("role", "page");
$("div").data("hidden", "true");
$("div").data("role", {name: "John"});

Reference: jQuery Documentation - .data()

2 .stop( [ clearQueue ], [ jumpToEnd ] )

jQuery.com - "When .stop() is called on an element, the currently-running animation (if any) is immediately stopped. If, for instance, an element is being hidden with .slideUp() when .stop() is called, the element will now still be displayed, but will be a fraction of its previous height. Callback functions are not called."

This method is extremely useful when dealing with animation. It able to terminate all existing animation, and play the most current one.

$(this).find('img').stop(true, true).fadeOut();

Reference: jQuery Documentation - .stop()

3 .toggleClass()

jQuery.com - "Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument."

This method allow you to toggle between class, for example, if you have an element with "active" class attached, when this method was used, it will switch it by toggle it on and off (if class exist, remove the class, otherwise put it back on)

$('#home').toggleClass('active');

Which is the same with the following:

if ($('#home').hasClass('active')) {
    $('#home').removeClass('active');
  }
  else {
    $('#home').addClass('active');
  }

Reference: jQuery Documentation - .toggleClass()

4 .delay( duration, [ queueName ] )

jQuery.com - "Added to jQuery in version 1.4, the .delay() method allows us to delay the execution of functions that follow it in the queue. It can be used with the standard effects queue or with a custom queue."

This method is really useful to give some delays in a series of animations.

$('#content').slideUp(300).delay(800).fadeIn(400);

Reference: jQuery Documentation - .delay()

5 .each()

jQuery.com - "The .each() method is designed to make DOM looping constructs concise and less error-prone. When called it iterates over the DOM elements that are part of the jQuery object. Each time the callback runs, it is passed the current loop iteration, beginning from 0. More importantly, the callback is fired in the context of the current DOM element, so the keyword this refers to the element."

//Given this HTML Structure
<ul>
	<li>Apple</li>
	<li>Orange</li>
	<li>Mango</li>
	<li>Blueberry</li>
	<li>Watermelon</li>
</ul>

//We can retrieve the value with:
$('li').each(function(index) {
    alert(index + ': ' + $(this).text());
});


//Alternatively, loop through JSON
var data = "{ name: "John", lang: "JS" }";

$.each( data, function(k, v){
   alert( "Key: " + k + ", Value: " + v );
});

Reference: jQuery Documentation - .each()

6 .size()

jQuery.com - "The .size() method is functionally equivalent to the .length property; however, the .length property is preferred because it does not have the overhead of a function call."

But, it still good to know anyway :)

//Given this HTML Structure
<ul>
	<li>Apple</li>
	<li>Orange</li>
	<li>Mango</li>
	<li>Blueberry</li>
	<li>Watermelon</li>
</ul>

var size1 = $("li").size();
var size2 = $("li").length;

Both of the examples above will return 5.

Reference: jQuery Documentation - .size()

7 .closest(selector)

jQUery.com - Get the first ancestor element that matches the selector, beginning at the current element and progressing up through the DOM tree.

$('li.item-a').closest('ul').css('background-color', 'red');

Reference: jQuery Documentation - .closest()

8 .position()

jQUery.com - The .position() method allows us to retrieve the current position of an element relative to the offset parent. Contrast this with .offset(), which retrieves the current position relative to the document. When positioning a new element near another one and within the same containing DOM element, .position() is the more useful.

var p = $("p:first");
var position = p.position();
alert("left: " + position.left + ", top: " + position.top);

Reference: jQuery Documentation - .position()

Author: Kevin Liew

Kevin Liew is a web designer and developer and keen on contributing to the web development industry. He loves frontend development and absolutely amazed by jQuery. Feel free to say hi to me, or follow @quenesswebblog on twitter.

Share the love

8 comments

Andrew
Wed, 16th March 2011
I think the data example has an error, should it not be:

$("div").data("type") === "page"; Reply
Raghibsuleman
Wed, 16th March 2011
Thanks for sharing...
http://www.raghibsuleman.com/ Reply
keshav
Thu, 5th May 2011
your code described in "each" block i tried with

var data = '{ name: "John", lang: "JS" }';
$.each( data, function(k, v){
console.log( "Key: " + k + ", Value: " + v );
});
gives below output:

Key: 0, Value: {
Key: 1, Value:
Key: 2, Value: n
Key: 3, Value: a
Key: 4, Value: m
Key: 5, Value: e
Key: 6, Value: :
Key: 7, Value:
Key: 8, Value: "
Key: 9, Value: J
Key: 10, Value: o
Key: 11, Value: h
Key: 12, Value: n
Key: 13, Value: "
Key: 14, Value: ,
Key: 15, Value:
Key: 16, Value: l
Key: 17, Value: a
Key: 18, Value: n
Key: 19, Value: g
Key: 20, Value: :
Key: 21, Value:
Key: 22, Value: "
Key: 23, Value: J
Key: 24, Value: S
Key: 25, Value: "
Key: 26, Value:
Key: 27, Value: }

not the expected...will you please explain??
Reply
yahoooo
Sun, 9th December 2012
Hey keshav,
What u have specified in var data is a string , hence the o/p, Instead use an array. Reply
keshav
Thu, 5th May 2011
also this one gives syntax error " options is not a method "

$("div").data("options").name === "John"; Reply
esteve
Thu, 5th May 2011
hi,

good article. Just point out to be carefull with ".each" method performance. You may get performance problems when iterating a "huge" amount of times. Dynatrace Ajax utility it's a good software to help on performance problems. Reply
Neil
Fri, 10th June 2011
@keshav--because you surrounded the value you're assigning to <em>data</em> with single quotes, JavaScript is interpreting <em>data</em> as a string rather than an object (a string that happens to have some strange characters in it, but a string nonetheless). Try it without the quotes, like this.

var data = {name: "John", lang: "JS"}; Reply
RumeshChanchal
Sat, 24th September 2011
Hello Everyone,
JQuery size () method is used to count DOM element’s by specifying matched elements. In this demo I am try to show you, how we can count specified DOM element s on the matched condition. In this demo multiple <option> element is define in <select> element and I want to count <option> element as a total number of cities.......... for more details check out the following link....
http://mindstick.com/Articles/15efbd16-6598-48c9-bf42-95195278b6d7/?JQuery%20size%20method

Thanks !!!!!! Reply

Leave a Comment

Please keep in mind that comments are moderated and rel="nofollow" is in use. You can use [code][/code] if you want to write codes. Don't spam us :) Thanks!

Advertisement