Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery ul li select list

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

like image 911
russell Avatar asked Jan 15 '10 11:01

russell


People also ask

How to select a particular element in jQuery?

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.

Which is the correct jQuery selector to select the first list item of ul element?

The :first selector selects the first element.

What is the use of CSS () method in jQuery?

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.


1 Answers

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;
});
like image 120
Tatu Ulmanen Avatar answered Sep 18 '22 13:09

Tatu Ulmanen