jskidd3
jskidd3

Reputation: 4783

Carousel using jQuery 'index' function

JavaScript:

$("nav ul li").click(function (){
    var index = $(this).attr('value');
    $("#pages").css('left', index + '%');
});

HTML:

<nav>
    <ul>
        <li id="about" class="selected inSelected" value="50">About</li>
        <li id="contact" value="-50">Contact</li>
        <li id="test" value="-150">YouTube</li>
    </ul>
</nav>

The code above does what I need it to do. Imagine a div in the middle of the page (left 50%). As you click a item in the list it shuffles it along by the 'value' attribute. Eg, clicking YouTube would set the left to -150% essentially moving the div along to other content.

My problem with this is it's not very efficient but my non-mathematical brain isn't helping me come up with a sensible solution. I want to achieve the same thing but without having to set specific values for each li. This should be more than possible use 'index()'.

$("nav ul li").click(function (){
    var index = $(this).index(); // this is the main difference
});

Let's say you click YouTube, index will be equal to 2. So now I need to get from 2 to -150. Fine, that's possible, but I need to use the exact same formula to get back to Contact with index 1.

If anyone could help I'd highly appreciate it.

Upvotes: 0

Views: 85

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

Try

$("nav ul li").click(function (){
    var index = $(this).index(); // this is the main difference
    var value = index * -100 + 50
});

like

index calc            value
0 =   0 * -100 + 50 = 50
1 =   1 * -100 + 50 = -50
2 =   2 * -100 + 50 = -150
3 =   3 * -100 + 50 = -250

Demo: Fiddle

Upvotes: 4

Related Questions