How to assign values to a jquery object using for loop - javascript

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

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

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);
});

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/

Related

How do I remove variable randomly using jquery?

I'm trying to find a way to remove variable from certain div on the web using jquery. This does not involve using array. If I can do so with using fadeIn() or search() and remove(), that's even better.
var something = '#img' + count;
on the web, images will be added to div as time passes (using setTimeout). Those images have been assigned to variable (something) and I need to find a way to remove it from certain div on the web. It can be hide, remove, whatever, it has to disappear from user's view randomly (both time and which image will disappear).
Thanks for help and your time in advance.
my function code:
var count = 0;
function foo() {
var xPos = xPosition();
var yPos = yPosition();
var someTime;
$("div").append('<img id="Img" ' + count + ' src = "img.png" style="top:' + yPos + 'px; left: ' + xPos + 'px; " />');
var something = "#Img" + count;
someTime = setTimeout('foo()', randInterval());
$(something).hide();
count++;
if (timeRemaining == 0) {
clearTimeout(someTime);
return;
}
Give all the images a class. You can then use $(".class").length() to get the number of images, pick a random number in this range, and delete that element with .eq().
function addImage() {
var xPos = xPosition();
var yPos = yPosition();
$("div").append($("<img>", {
src: "img.png",
"class": "imageclass",
style: {
top: yPos+"px",
left: xPos+"px"
}
}));
setTimeout(addImage, randInterval());
}
setTimeout(addImage, randInterval());
function removeImage() {
var images = $(".imageclass");
if (images.length) {
var rand = Math.floor(Math.random() * images.length);
images.eq(rand).remove();
}
setTimeout(removeImage, randInterval());
}
setTimeout(removeImage, randInterval());
In my code I'm using separate timers for adding and removing images. If you prefer, you could remove the setTimeout from removeImage(), and just call it from addImage so it will always remove an image whenever it's adding a new one.
Please, never ever append a number to an id and piece together numbered names of things. It is unmaintainable and bad. Use class.
Assign a purpose or functionality to an element or elements by adding a class name to them. If you want to add information to an element, that is great, use data- prefix on the attribute name and it is all legal. data-itemid is an example.
You can query for matching elements with var those = $('.that-class-name'), stored for reuse. From there you can access individual elements using those.eq(0) through those.eq(x.length - 1). For example, if you somehow knew that the 3rd one needs to be removed, then those.eq(3).remove();. If you want to pick through them and only select ones that match a condition, use those.filter(callback).remove(), where callback returns true if the element referred to by this should be removed. If you want to filter those with another selector, .filter will accept a selector too.
Is that what you meant?

Increment style.marginLeft with each click?

I'm building a basic slider with JavaScript. Each time button is clicked, div slide should increment its margin-left "-100px".
I have this code:
document.getElementById('core-next').onclick = function() {
document.getElementById('slides').style.marginLeft = "-100px";
}
And it works in a way that when I click #core-next margin gets set to -100px.
But what I want to achieve is that every time I click a button, margin increases by -100px.
So it looks like: -100px, -200px, -300px...
Is this possible in pure JavaScript? jQuery has "+="! Can I do this in Javascript wihout adding additional variable?
I tried this:
document.getElementById('core-next').onclick = function() {
document.getElementById('slides').style.marginLeft -= 200 + 'px';
}
But its not working...
Is there a way to achieve this in JavaScript, without creating additional variable that will hold margin value?
Thanks!
That property is a string so first you need to read it, parse it to a int and then change the value and reset it. Something like this:
document.getElementById('core-next').onclick = function() {
var slides = document.getElementById('slides');
// Read it and parse to an int
var marginLeft = parseInt(slides.style.marginLeft, 10);
// Subtract value, add pixel back in and reset property
slides.style.marginLeft = (marginLeft - 100) + 'px';
}
If you really need it in one line you could do this:
document.getElementById('slides').style.marginLeft = (parseInt(document.getElementById('slides').style.marginLeft, 10) - 100) + 'px';
But this solution while it doesn't have a variable holding the value and is one line isn't great since it calls getElementById twice for same value.
you can use parseInt function to remove px from marginLeft string. First parameter is the input string and the second one is the radix.
var slides = document.getElementById('slides');
document.getElementById('core-next').onclick = function() {
slides.style.marginLeft = (parseInt(slides.style.marginLeft, 10) - 100) + 'px';
}

How to use a data identifier on an array of divs?

Hi there I'm currently building a slider and I got pretty much all nailed down except one last thing.
My bullet points are identifying what image you are currently looking at and can also be used for navigation as illustrated here (2 sliders since this is where im running into issues):
http://puu.sh/hAYp5/15477cd325.png
For the actual dots I've been able to use this code:
$(this.dots).click(function() {
var selected = $(this).data("img");
sliderEle.goTo(selected);
$(dots).removeClass("active");
$(this).addClass("active")
})
The prev and next buttons however I'm having an issue figuring out, this is what I currently got and it affects both sliders as it is none specific to the individual slider like I want it to be:
goTo: function(index) {
if (index < 0)
return;
// move <ul> left
this.ul.style.left = '-' + (100 * index) + '%';
this.currentIndex = index
},
goToPrev: function() {
this.goTo(this.currentIndex - 1)
$(this.dots).removeClass("active");
$('.slider-dot[data-img="'+this.currentIndex+'"]').addClass("active");
},
goToNext: function() {
if(this.currentIndex + 1 > this.li.length - 1) {
this.goTo(0)
}else {
this.goTo(this.currentIndex + 1)
}
$(this.dots).removeClass("active");
$('.slider-dot[data-img="'+this.currentIndex+'"]').addClass("active")
}
How do I change this line:
$('.slider-dot[data-img="'+this.currentIndex+'"]').addClass("active")
To work with something like this:
$(this.dots)
So it's targeted on the individual slider rather than all sliders.
Full js source: http://pastebin.com/NaDw0jib
Solved by using .filter from jquery
var currentDot = $(this.dots).filter('[data-img="'+this.currentIndex+'"]');
$(currentDot).addClass("active");
add a function to your prototype
getNav: function(index) {
return $(this.nav).filter(function() {
return $(this).data('img') === index;
});
});
ten use it like this:
this.getNav(3).addClass('active');
As an aside, I'd probably either expand the initialize method to actually create the DOM representation, or failing that, at least use classes rather than hard coding to children[i] references. It'll save you a headache later.

javascript css call by variable not working in Android browser

I am looping through a set of images, and then setting their height to match a variable. The following code is working just fine with Firefox, however is unresponsive in Android's browser. Thoughts?
var x = 100;
count_li = 5;
for (var i = count_li - 1; i >= 0; i -= 1) {
var carousel_img = '#carousel_img_' + [i];
$(carousel_img).css('height', x);
}
Where I have a set of 5 images that might look like this:
<img id="carousel_img_0" src="img_0.jpg"/>
<img id="carousel_img_1" src="img_1.jpg"/>
etc...
Here is a similar post for reference, but I'm not finding what I need in it.
A secondary, directly connected issue is that this code is having the exact issue:
var img_w = $(carousel_img).width();
Presumably it too needs a 'px' reference, but I'm unaware of the syntax.
Solutions ----------------------------------------------------------
As stated by Matt, this
$(carousel_img).css('height', x);
needed to have a 'px' added to the end, as seen below:
$(carousel_img).css('height', x + 'px');

Javascript style.left is empty string

next.onclick = function() {
move('left', li_items[0]);
};
var move = function(direction, el) {
pos = el.style[direction].split('px')[0];
pos = parseInt(pos, 10) + 10;
el.style[direction] = pos + 'px';
};
I'm using the simple code above to try and move an element. Now when I breakpoint on this, the value of el.style[direction] is: " ". So then when i try to do anything with it, it breaks. Why would this be? Isn't style.left supposed to return an integer?
Why would this be?
Presumably because it hasn't been set to anything.
Isn't style.left supposed to return an integer?
No. It is supposed to return a string containing the value of the CSS left property as set directly on the element (either by setting the JS property itself or by using a style attribute). It does not get a value from the cascade and it should only be an integer if the value is 0 (since all other lengths require units).
See How to get computed style of a HTMLElement if you want to get the computed value for the property rather than what I described in the previous paragraph.
style provides the original style as calculated from the CSS, not the updated and possibly dynamic style. You probably want currentStyle instead.
next.onclick = function() {
move('left', li_items[0]);
};
var move = function(direction, el) {
var lft = document.defaultView.getComputedStyle(el)[direction];
pos = parseFloat(lft);
pos = parseInt(pos, 10) + 10;
el.style[direction] = pos + 'px';
};
Note: like Elliot said you'll have to get the currentStyle/computedStyle. Here's a way to make it cross-browser, however when applying styles via JS, this is one good case where some sort of framework (eg Prototype [Scriptaculous], jQuery) would be useful.
Just a comment.
In your code:
> pos = el.style[direction].split('px')[0];
> pos = parseInt(pos, 10) + 10;
The split in the first line is superfluous, in the second line parseInt will convert (say) 10px to the number 10 just as effectively (and more efficiently) than what you have.
pos = parseInt(el.style[direction], 10);

Categories

Resources