etangins
etangins

Reputation: 624

Combine Series of If Statements into one Code

Right now I have a series of if statements, each one testing if the window is scrolled past a certain point, and if it is, the background is changed. Since each if statement is very similar, I'm wondering if I can combine all the if statements into one. Since I have over a hundred images, with this method I'm currently using, I would have to make one if statement for each image.

A sample of my code is below. The only things that change you'll notice is the scrolltop()/2 > _ and MAH00046%2028.jpg.

    if ($(this).scrollTop()/2 > 2800) {
    $('body').css({
        backgroundImage: 'url(    "images/chapter_background_images/MAH00046%20028.jpg")'
    });
}

if ($(this).scrollTop()/2 > 2900) {
    $('body').css({
        backgroundImage: 'url(    "images/chapter_background_images/MAH00046%20029.jpg")'
    });
}

Upvotes: 1

Views: 114

Answers (3)

Cameron Tinker
Cameron Tinker

Reputation: 9789

This will work best:

var imageBase = 'images/chapter_background_images/MAH00046%200';            
var scrollTopHalf = $(this).scrollTop() / 2;
if(scrollTopHalf < 2900 || scrollTopHalf > 3900)
{           
    var image = imageBase + (Math.floor(scrollTopHalf / 100)).toString() + '.jpg';

    $('body').css({
        backgroundImage: 'url("' + image + '")'
    });
}

My other approach was largely inefficient.

Upvotes: 3

Slight variation using a for loop and assuming increments of 100 with a base of 2800 (and incrementing each jpg filename's number successfully by 1

function myFunction() {
var counter = //number of if statements
for (i = 28; i <= i + counter; i++) {
    if ($(this).scrollTop()/2 > 100*i) {
        $('body').css({backgroundImage: 'url("images/chapter_background_images/MAH00046%200"' + i + '".jpg")'});
    }
}

Upvotes: 0

ESD
ESD

Reputation: 544

Instead of using if statements, use the result of the calculation to create the link to the picture since the name of the pictures are sequential numbers.

var inc = 100;
var imgUrl = 'images/chapter_background_images/MAH00046%';
var url = imgUrl.concat((Math.floor(scrollTop()/2)/inc)*inc).toString());

I am using 100 here but you can change this value for the value of each increment between your pictures.

javascript floor method

javascript concatenate method

Javascript tostring method

Upvotes: 1

Related Questions