Johnny Derp Johnny Derp - 1 month ago 22
jQuery Question

jQuery select ul li items with next prev buttons

I'm trying to select li element with prev next buttons, currently using this code: http://jsfiddle.net/KzyAY/41/ but if you keep clicking next/prev it keeps going out of the ul element. any idea how i select inside ul ? Thanks!

here fiddle: http://jsfiddle.net/KzyAY/41/

<ul class='selected' id="">
<li id="">1</li>
<li id="">2</li>
<li id="">3</li>
</ul>
<div>Current tag:<span id="current-tag"></span></div>
<button id="prev">Previous</button>
<button id="next">Next</button>


js:

(function($) {
$.fn.domNext = function() {
return this
.children(":eq(0)")
.add(this.next())
.add(this.parents().filter(function() {
return $(this).next().length > 0;
}).next()).first();
};

$.fn.domPrevious = function() {
return this
.prev().find("*:last")
.add(this.parent())
.add(this.prev())
.last();
};
})(jQuery);

$("#next").click(function() {
var $next, $selected = $(".selected");

$selected.removeClass("selected");
$next = $selected.domNext().addClass("selected");
if ($next.length) {
$("#current-tag").text($next.attr('class'));
}
});

$("#prev").click(function() {
var $prev, $selected = $(".selected");
$selected.removeClass("selected");
$prev = $selected.domPrevious().addClass("selected");
if ($prev.length) {
$("#current-tag").text($prev.get(0).tagName);
}

});

Answer

Not sure about the plugin.. As that is surely an overkill for something simple.

But I would just write this up

var $first = $('li:first', 'ul');
var $last = $('li:last', 'ul');

// Have the first and last li's set to a variable
$("#next").click(function () {

    var $next;
    var $selected = $(".selected");
    // get the selected item
    // If next li is empty , get the first
    $next = $selected.next('li').length ? $selected.next('li') : $first;
    $selected.removeClass("selected");
    $next.addClass('selected');
});

$("#prev").click(function () {
    var $prev,
        $selected = $(".selected");
    // get the selected item
    // If prev li is empty , get the last
    $prev = $selected.prev('li').length ? $selected.prev('li') : $last;
    $selected.removeClass("selected");
    $prev.addClass('selected');
});

Check Fiddle