Trying to use JQuery to scroll through a ul li list using class next and class prev e.g.
<ul class="selectoption">
<li> Item 1</li>
<li> Item 2</li>
<li> Item 3</li>
<li> ... </li>
</ul>
<a href="" class="next">Next</a>
<a href="" class="prev">Back</a>
Only thing is I only want the selected li to be visible. So somehow need to index the li's? Help much appreciated - thanks in advance
The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.
The :first selector selects the first element.
jQuery css() Method The css() method sets or returns one or more style properties for the selected elements. When used to return properties: This method returns the specified CSS property value of the FIRST matched element.
This should do it:
// Hide all but the first
$('.selectoption li').not(':first').hide();
// Handle the click of prev and next links
$('.prev, .next').click(function() {
// Determine the direction, -1 is prev, 1 is next
var dir = $(this).hasClass('prev') ? -1 : 1;
// Get the li that is currently visible
var current = $('.selectoption li:visible');
// Get the element that should be shown next according to direction
var new_el = dir < 0 ? current.prev('li') : current.next('li');
// If we've reached the end, select first/last depending on direction
if(new_el.size() == 0) {
new_el = $('.selectoption li:'+(dir < 0 ? 'last' : 'first'));
}
// Hide them all..
$('.selectoption li').hide();
// And show the new one
new_el.show();
// Prevent the link from actually redirecting the browser somewhere
return false;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With