Skip to content Skip to sidebar Skip to footer

Jquery: Next() And Prev() With A Wrapper?

I have the following html:

Solution 1:

The easiest way to select the "real" next <article> elements is by using the .index and .eq methods.

var allArticles = $("article.layer");
var index = allArticles.index(view);   // Zero-based indexes. Not found = -1
var prev = index <= 0 ? $() : allArticles.eq(index-1);
var next = allArticles.eq(index + 1); 

Solution 2:

Get a collection of all the articles, then on keypress find out which article is the current one and calculate next/prev based on their relative position(index) from the current article. You'll need to be careful in handling the first/last article.

var $articles = $('.article');

$(document).keydown(function(e) {

    var view = $('.layer:in-viewport'),
        idx = $articles.index(view),
        prev = $articles.eq(Math.max(0,idx-1)),
        next = $articles.eq(Math.min(idx+1,$articles.length-1));

    switch (e.keyCode) {
        case38: // Upif ( prev != undefined )
                scroll($("#"+prev), true, 0);
            break;
        case40: // Downif ( next != undefined )
                scroll($("#"+next), true, 0);
            break;
    }

});

You could also implement wrapping at the ends if you wanted.

Post a Comment for "Jquery: Next() And Prev() With A Wrapper?"