SKB
SKB

Reputation: 11

Jquery animate till a condition is met

I have the following code for moving the product-details-content div by 100% every time I click on product-prev-button. This code works fine except for it keeps scrolling forever. I want it to stop scrolling when the marginLeft is more than -400%. Can I introduce a condition somewhere to get it working?

$(document).ready(function(){
    $("#product-prev-button").click(function(){
        $("#product-details-content").animate({
            marginLeft: '-=100%'
        });
    });
});

Upvotes: 1

Views: 781

Answers (3)

SKB
SKB

Reputation: 11

I could get it working by doing slight modicifation to the code provided by "MGA".

$(document).ready(function(){
$("#product-prev-button").click(function(){
    var prevvalue1 = parseInt($("#product-details-content").css('margin-left'));
    var prevvalue2 = parseInt($("#product-details-content").outerWidth());
    var prevvalue=-(prevvalue1/prevvalue2);
    if(prevvalue < .75)
    {
        $("#product-details-content").animate({
        marginLeft: '-=100%'
         });
     }
 });               

});

Upvotes: 0

MGA
MGA

Reputation: 531

    $("#product-prev-button").click(function(){
             var value = parseInt($("#product-details-content").css('margin-left'));                                  
             console.log(value);
             if(value > -400)
             {
                $("#product-details-content").animate({
                    marginLeft: '-=100%'
                });
             }

            });               
        });

Upvotes: 1

rgajrawala
rgajrawala

Reputation: 2188

Just use a counter...

var MAX_CLICKS = 4;

$(function() {
    var clickCounter = 0;

    $("#product-prev-button").click(function() {
        // only move -100% if we are under or at 4 clicks (-400%)
        if (++clickCounter <= MAX_CLICKS) {
            $("#product-details-content").animate({
                marginLeft: '-=100%'
            });
        }

        // do other stuff regardless ...
    });
});

Upvotes: 1

Related Questions