Later Today: ASP.NET Tutorial 2: Introduction to C#

(jQuery) .nextOrFirst() function guarantees a selection

For instance, a function that is triggered at least once at some point, and then automatically executes itself again each time it finishes.
Prerequisites: jQuery must be loaded before using code snippet. Some experience with jQuery is necessary.

The .nextOrFirst() jQuery function/plugin detailed here works as an alias for .next(), except when there are no more objects for .next() to select. When this happens, .nextOrFirst() will automatically select the first sibling (essentially treating the first element as “next”).

By itself, .next() is used, not surprisingly, to change any current selection to that selection’s next sibling (you can read more about it here). By default, if .next() is used on the last element within any given parent (for instance, the last <li> in a <ul>), it will return nothing. But what if you want to ensure that .next() always returns a selection? For instance, what if we want to get the first <li> if we reach the last one?

Occasionally I run into scripting situations where I need this very functionality – particularly if I’m scripting something that works on a loop. To make my life easier, I wrote this very simple jQuery extension that does just what I need – automatically select the first item if there’s no .next() left to select.

jQuery: .nextOrFirst()
/********************************************************************************
 * jQuery.nextOrFirst()
 *
 * PURPOSE: Works as alias for .next() until there are no more
 * siblings left to select, then it starts over, selecting
 * the first element from the current list the siblings.
 ********************************************************************************/
jQuery.fn.nextOrFirst = function(selector){
    if(jQuery(this).next().length === 0){
        return jQuery(this).parent().children(':first').filter(selector);
    }else{
        return jQuery(this).next(selector);
    }
}

Remember that in order to use this function, jQuery must already be loaded. This could also be easily tweaked into a .prevOrLast() function.

No Comments

Post a Comment

You must be logged in to post a comment.

RSS Twitter LinkedIn Facebook
Doing neato things with JavaScript, please wait...