views:

49

answers:

1

Hello guys,

I've created a very basic slider with jQuery. There are two arrows called .theleft and .theright, which are moving some div contents when clicked, so an horizontal gallery full of images moves from side to side at a 950px range. This is the code:

$(".theright").click(function() {               
$(".mymove").animate({ 
        left: "-=950px",
      }, 1500 );
});

$(".theleft").click(function() {                
$(".mymove").animate({ 
        left: "+=950px",
      }, 1500 );
});

The HTML is very simple:

<div class="mymove" style="position:relative">
    <ul>
        <li>
            <img src="" title="" alt="">
        </li>
        <li>
            <img src="" title="" alt="">
        </li>
        <li>
            <img src="" title="" alt="">
        </li>
        <li>
            <img src="" title="" alt="">
        </li>
    </ul>
</div>

My question is, when the page loads, if the first thing I do is clicking the left arrow, the gallery gets off the viewport getting lost at the right side, that is, I haven't found a way to 'limit' the slider action...

Do you know of some way to improve that?

Many thanks.

+1  A: 

You will need some sort of counter that will keep track of where your slider is up to.

So if it initially starts at 0 have something like this:

$(".theleft").click(function() {                
    if (slider_pos > 0) {
        $(".mymove").animate({ 
            left: "+=950px",
        }, 1500 );
        // Then update slider_pos here i.e. view_pos += 950;
    }
});
xiaohouzi79
Thanks! Just a question, how would be the syntax to determine the "slider_pos" value? Something like using php? Should I calculate it before anything else inside the jquery snippet right? Something like var slider_pos = <?php numberofimages(); ?>
Peanuts
You may want to use a global javascript variable, so don't use var when declaring slider_pos.Also don't use php inside your javascript, it's bad practice, mainly because it's unreliable.What you should do is use jquery (or javascript) to count the number of image elements. Something like this:var num_images = $(".mymove ul li img").length
xiaohouzi79