user2751288
user2751288

Reputation: 188

For loop in javascript to catch multiples of 200

I currently have this code which checks the margin-left of the navigation, and scrolls it left accordingly. However, this method is slow, so I would like to know how to change it into a for loop or something of the sort to catch every multiple of 200 then animate the navigation accordingly.
This is my code currently, as you can tell not very efficient if this needs to go up to -5000 ect.
EDIT
These are my functions, but they do not work

    function goleft(){
    var nav = $("#innernavigation");
    var navmargin = parseInt(nav.css("margin-left"), 10);
    if (navmargin != 0)
    {
        //time!
        if (navmargin > -nav.width() && navmargin < -200)
        {   
            nav.animate({'marginLeft':'-' + ((Math.floor(navmargin / 200)-1) * 200) + 'px'});
        }
        if (navmargin > 0)
        {
            nav.css({'marginLeft':'0px'});
        }
    }
}
function goright(){
    var nav = $("#innernavigation");
    var navmargin = parseInt(nav.css("margin-left"), 10);
    if (navmargin != -nav.width())
    {
        //time!
        if (navmargin > 0 && navmargin < -nav.width())
        {   
            nav.animate({'marginLeft':'-' + ((Math.floor(navmargin / 200)-1) * 200) + 'px'});
        }
        if (navmargin < -nav.width())
        {
            nav.css({'marginLeft':'-' + nav.width()});
        }
    }
}

Upvotes: 1

Views: 210

Answers (3)

Torben
Torben

Reputation: 6857

Just a fast guess (not tested yet):

if (navmargin<-200 && navmargin>-5000) {
    nav.animate({'marginLeft':((navmargin%200-1)*-200)+'px'});
}

Upvotes: 0

Adil
Adil

Reputation: 148160

You can do something like this in single if statement.

if (navmargin > -5000 && navmargin < -200)
{
    nav.animate({'marginLeft': (-((Math.floor(navmargin / 200)-1) * 200) + 'px'});
}

Upvotes: 2

tarkeshwar
tarkeshwar

Reputation: 4155

nav.animate({'marginLeft': (Math.floor(Math.abs(navmargin) / 200) * -200) + 'px'})

Upvotes: 0

Related Questions