Shniper
Shniper

Reputation: 854

How to assign values to a jquery object using for loop

I have tried several ways to create a parallax effect on my images where each image has it's own random speed. I think the best way for me to achieve it is by assigning a speed value to each image. However I am not sure how to do this.

var img_list = [];
$.each($('.gallery_image'), function(e) {
    img_list.append($(this));
});

for(x in img_list) {
    ran = Math.round(Math.random() * (11 - 1) + 1);
    speed = ran.toString() + "px";
    x.speed = speed;
}

This is what I came up with. I know that x.speed is not an actual thing, but I am using that to illustrate what I am trying to accomplish.

This is a website that has exactly what I am looking for on the main page, but I want the movement to be on scroll. EXAMPLE

Upvotes: 1

Views: 122

Answers (3)

vikrant singh
vikrant singh

Reputation: 2111

I dont know if this is relative or not ,but I made a demo . Hope this helps.

To move image set left css property of dom.

DEMO

https://jsfiddle.net/vikrant47/yem6f0Ls/4/

Upvotes: 1

madalinivascu
madalinivascu

Reputation: 32354

Use push

var img_list = [];
$.each($('.gallery_image'), function(e) {
    img_list.push($(this));
});

but in this case you don't need a loop because $('.gallery_image') is a collection of objects

In the second loop you can use a each loop and save the speed as a data attribute:

$('.gallery_image').each(function(i,x){
    ran = Math.round(Math.random() * (11 - 1) + 1);
    speed = ran.toString() + "px";
    $(x).data('speed',speed);
});

Upvotes: 1

Joe Horn
Joe Horn

Reputation: 443

for(var x in img_list) {
    var ran = Math.round(Math.random() * (11 - 1) + 1);
    img_list[x].speed = ran.toString() + "px";
}

Upvotes: 2

Related Questions