jQuery Minute™

…a jQuery Minute™ later and you're done!

Archive for the ‘jQuery 101’ Category

jQuery add or remove class with toggleClass

without comments

Back in May of 2008 I posted about how to dynamically call a jQuery function and the practical use in adding or removing a class in one fell swoop. Since that post the toggleClass method has been updated to accept a second argument, a boolean value to signify adding or removing a class.

First the classic toggle class example:

1
$('body').toggleClass('blue');

Which just as the method describes will add the class “blue” if it doesn’t exit or remove it if it does.

In the next example we make use of addClass or removeClass

1
2
3
4
5
if ( $('body').hasClass('makeBlue') ) {
    $('body').removeClass('blue');
} else {
    $('body').addClass('blue');
}

Which has the same result and function as our first example with the difference that we’re adding or removing a class based upon the condition of body having the class “makeBlue”.

So here is an updated example making use of toggleClass along with the second argument that when true adds the class and conversely if false removes the class.

1
2
var addBlue = $('body').hasClass('makeBlue');
$('body').toggleClass('blue', addBlue );

And the final reduced version:

1
$('body').toggleClass('blue', $('body').hasClass('makeBlue') );

Cheers,
– Jonathan

Written by jdsharp

October 3rd, 2009 at 12:13 am

Finding Immediately Adjacent Siblings

without comments

Greetings! Here’s a quick tip for advanced filtering of adjacent sibling nodes.

Given the following HTML:

1
2
3
4
5
6
7
8
<ul>
    <li>Item 1</li>
    <li class=”hello”>Item 2</li>
    <li class=”hello” id=”three”>Item 3</li>
    <li class=”hello”>Item 4</li>
    <li>Item 5</li>
    <li class=”hello”>Item 6</li>
</ul>

If you needed to select the immediate siblings of #three that matched the class .hello (so the resulting element set would be Item 2, Item 3, Item 4) there isn’t an easy way to do this. jQuery provides a prev() and prevAll() methods (as well as their next() counter parts) but that would return all of the elements. Here’s a jQuery immediateSiblings function to take care of this for us:

$(‘#three’).immediateSiblings(‘li.hello’)

Here’s the code for the plugin:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/*
 * immediateSiblings 1.1.0 (2009-10-19)
 *
 * Copyright (c) 2006-2009 Jonathan Sharp (http://jdsharp.com)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://jdsharp.com/
 *
 * Built upon jQuery 1.3.2 (http://jquery.com)
 */
$.fn.immediateSiblings = function(selector) {
    var siblings = [];
    this.each(function() {
        var children = $(this).parent().children(selector).not(this).get();
        $.merge(siblings, children);
    });
    return this.pushStack( $.unique( siblings ) );
};

Cheers,
-Jonathan

Written by jdsharp

July 14th, 2008 at 8:34 pm

jQuery as an Associative Array – Dynamically calling jQuery functions

without comments

So how many times have you done the following:

1
2
3
4
5
6
var elm = $('.selector');
if ( elm.hasClass('selectedElement') ) {
    elm.removeClass('abc');
} else {
    elm.addClass('abc');
}

One alternative to the above example is to use jQuery’s toggleClass() method, but toggleClass does exactly that, toggles the class without a way for us to know the current state.

So now to the point of this post, accessing a jQuery function using associative array notation. Here’s an example of a typical jQuery operation:

1
2
// Call addClass('abc') on all divs
$('div').addClass('abc');

Here’s the same jQuery operation using associative array notation.

1
2
// Call addClass('abc') on all divs using associative array notation
$('div')['addClass']('abc');

Now the refactored example from the beginning of this post:

1
2
var elm = $('.selector');
elm[ ( elm.hasClass('selectedElement') ? 'remove' : 'add' ) + 'Class' ]('abc');

Here’s some additional links on JavaScript objects as Associative Arrays:

Written by jdsharp

May 15th, 2008 at 2:37 pm

jQuery Iteration and each()

without comments

There was a recent thread on the jQuery discussion group in that there was a need for looping through a series of elements and dynamically binding an event. An issue was brought up with closures and the arguments for dynamic binding of functions. Brandon Aaron provided an elegant solution that makes use of jQuery’s internal each() function. Let’s jump in!

So here’s a paraphrase of Brandon’s code:

Example 1:
jQuery.each( [0,1,2,3,4], function(index, item){
// Your code
});

At first glance this may look the same as your standard iteration code using each but it differs slightly and that is where the benefit is. Let’s look at using the standard each method on a jQuery object:

Example 2:
$(‘selector’).each(function(index){
// Your code
});

In this example jQuery internally manages the collection (array) of matched elements by the selector.

But, by using jQuery’s internal .each() method (Example 1) we’re able to pass in an arbitrary array in which each item will have the callback executed. An elegant solution to your typical for ( i ) loop. Your callback can accept two arguments: index, item where index is the numerical zero based index in the array of the current item and item is the value of the current array. Also worth noting is that by returning false from you callback you can stop iteration over the array (this is the same as using a break; statement in a for loop).

Happy coding!

Written by jdsharp

February 7th, 2008 at 8:00 am

jQuery parent() vs. parents()

without comments

Welcome jQuery newbies! I’m writing a quick post here to help clarify some differences between the parent() and parents() methods.

Given the following HTML:
<html>…<body><div class=”one”><div class=”two”><p><span>Some text</span></p></div></div></body></html>

$(‘span’).parent() will select the <p> tag such that the element set in the jQuery object is [span].

$(‘span’).parents() will select all parent tags such that the element set in the jQuery object is [p, div.two, div.one, body, html].

So parent() will select the first parent element while parents() will select all elements straight up the DOM tree.

Now jQuery has some great flexibility in that you could do that following:

$(‘span’).parents().filter(‘div’) which would result in [div.two, div.one]. jQuery makes it even easier as the parent() and parents() methods support filtering built in so the above can be reduced to:

$(‘span’).parents(‘div’) giving you [div.two, div.one].

Let’s continue with one more example, let’s say that you only need the first div in the parent DOM tree, jQuery to the rescue $(‘span’).parents(‘div:eq(0)’) will give you [div.two]

-Jonathan

Written by jdsharp

January 24th, 2008 at 10:34 am