Marek Ekes
Marek Ekes

Reputation: 65

Image slider in jQuery with actual slides as next/prev triggers

I'm a designer, have only a slight idea about jQuery. But I love learning :) So I decided to do the below thing myself, and I can't quite get it to work.

My idea is to have a slider with actual slides as next/prev buttons. So I can go to next slide by clicking the actual next slide - the same for previous slide. I guess the picture below shows what I mean.

Desired effect

I've tried to do it this way:

  1. assign a class .main to the main image
  2. assign a class .prev to the partially hidden image on the left
  3. assign a class .next to the partially hidden image on the right

And when I click .next, I change classes .main > .prev, .next > .main, .next +1 > .next.

Now I can do it one step up and it works, the classes change and it works fine. But then when I click the now-.next class, jQuery seems to not recognize it's .next now and responds to it as if it were still the .main class. The updated classes don't respond (the now- .main class still works as .next, as if jQuery was not reading the change).

Here's the HTML:

<div class="view">
    <ul>
        <li class="left" data-id="1"></li>
        <li class="main" data-id="2"></li>
        <li class="right" data-id="3"></li>
        <li data-id="4"></li>
        <li data-id="5"></li>
    </ul>
</div>

And the script:

$(".next").click(function(){
    $(this).prev().removeClass("main").addClass("prev");
    $(this).removeClass("next").addClass("main");
    $(this).next().addClass("next");
    $(".view ul li:first").animate({marginLeft: '-=57%'});
    $(".view ul li.main").animate({marginLeft: '-=15%'});
});

I guess it's toddler talk for you, but perhaps you could help me get it to work. How would you come about the matter? Any ideas?

Big thanks up front!

Cheers!

Upvotes: 4

Views: 111

Answers (1)

Niki van Stein
Niki van Stein

Reputation: 10724

It is not really toddler talk because there are a few pitfalls you need to be aware of.

First of all, the click handler will not work for the new .next this way. You need to use

$('body').on('click', 'li.next', function() {

instead to make it work for dynamic content.
Another problem is that you forgot to remove the .prev class

$(".prev").removeClass("prev");

Another small mistake is: $(".view ul li:first").animate({marginLeft: '-=57%'}); which always takes the first element, but after the first slide it should take the .prev instead. (so change it to li.prev). I guess btw that you use class="prev" instead of left (typo in question).

See the full code here: http://jsfiddle.net/a8Lf9r68/3/


And as @Mō Iđɍɨɇƶ says, you need some additional code to handle the last and first element clicks. But that depends on what you want, and I see it as outside the scope of the question.

Upvotes: 4

Related Questions