Using jQuery to switch background position every 250px - javascript

I'm new to jQuery and not sure best way to change the background position, i basically need to change a background position every 0 -250px, then 0 -500px etc. What is the best way to do this?
JS:
function startAvatarAnimation() {
var avatarHeight = 250;
var avatarTotalHeight = 2750;
var i = 0;
var avatarSpeed = 1000;
setInterval(function(){
i++;
if(i > avatarArray.length){
i = 0;
}
$(".avatars").css({'background-position' : '0 -' + (i*avatarHeight) + 'px' });
}, avatarSpeed);
}
HTML:
<div class="avatars"></div>
I'm getting an error at the moment with avatarArray is not defined, this is my first attempt. I guess it needs to work out the height so it knows when to stop as well?

Fixed with the following solution:
function startAvatarAnimation() {
var avatarHeight = 250;
var avatarTotalHeight = 2750;
var i = 0;
var avatarSpeed = 500;
var avatarArray = {};
setInterval(function(){
i++;
if(i > avatarArray.length){
i = 0;
}
$(".avatars").css({'background-position' : '0 -' + (i*avatarHeight) + 'px' });
}, avatarSpeed);
}

Related

Get elements coordinates

I need some help here.
First off, here is a small demo code from my game: https://jsfiddle.net/MiloSx7/a0dn9a4f/2/
Animation idea: Make the coin scale to 2x after it's collected, then slowly move it and gradually reduce scale to the exact spot where the image displaying the coin inventory stat is , invLocation is the ID of the element where the animation should end. It starts from the current coinId X and Y
Is it possible to somehow get the X and Y of the invLocation, so that I know where should I tell the animation to move?
You can do this with JQuery position() and offset() methods.
const spawnTime = 10000;
var coin = 0;
var intervalId = '';
var coinDiv = $('#coinDiv');
var coinImg = $('#coinImg');
var invDiv = $('#invDiv');
var invId = $('#inventoryId');
var invImg = $('#invLocation');
coinImg.on('click', collect);
intervalId = setInterval(setLocation, spawnTime);
function setLocation() {
var x = parseInt( Math.random()*(80-20+1) ) + 20;
var y = parseInt( Math.random()*(80-20+1) ) + 20;
coinImg.animate({
opacity: 1
}, 3000,
function() {
coinImg.css('top', x+'%');
coinImg.css('left', y+'%');
coinImg.css('display', 'initial');
setTimeout( () => coinImg.animate({ opacity: 0 }, 3000), 6000);
});
}
function collect() {
clearInterval(intervalId);
coinImg.stop();
coinImg.css('opacity', 1);
/* Increment coin counter */
coin++;
invId.text(coin);
/* In order to disable multiple clicks */
coinImg.css('pointer-events', 'none');
/* Double the size */
coinImg.css('width', '128px');
coinImg.css('height', '128px');
/* Animate and return to normal */
coinImg.animate({
width: '32px',
height: '32px',
left: invImg.offset().left + 'px',
top: invImg.offset().top + 'px'
}, 1500,
function() {
coinImg.css('pointer-events', 'auto');
coinImg.css('display', 'none');
coinImg.css('width', '64px');
coinImg.css('height', '64px');
intervalId = setInterval(setLocation, spawnTime);
}
);
}
Working example: https://jsfiddle.net/wz4q9w69/

iScroll not horizontally scrolling entire width of div

iScroll is not horizontally scrolling the entire width of a div. It stops at the wrong width value which I can't seem to find where that value originates from. The main scroll div width is not changing so I don't need to call refresh().
Essentially I've got a div inside the scroll div that is changing size so divs inside can be changed to absolute position while other divs inside are initially floated right. I didn't want to use iScroll but it's necessary since I'm building an HTML5 iOS WebView app with Trigger.io.
http://jsfiddle.net/simpleshadow/wQQEM/15/
var myScrollers = [];
$(function() {
var scrolls = $('.scrolls');
$.each(scrolls, function(i, value) {
var self = this,
imageDiv = $(this).find('.imageDiv'),
imageWrapper = $(this).find('.imageWrapper'),
images = $(this).find('.imageDiv img'),
width = 0;
$.each(images, function(index, value){
width += $(this).width();
});
imageDiv.css('right', (-$(this).width()+images.first().width()) + 'px');
imageWrapper.width(images.first().width());
myScrollers[i] = new iScroll($(this)[0], {
hScroll: true,
vScroll: false,
hScrollbar: false,
vScrollbar: false,
onScrollMove: function(e){
var x = 0;
-myScrollers[i].x >= 0 ? x = -myScrollers[i].x : x = 0;
updateWindow($(self), x);
},
onScrolling: function(e) {
var x = 0;
-myScrollers[i].x >= 0 ? x = -myScrollers[i].x : x = 0;
updateWindow($(self), x);
}
});
});
// Update the window
function updateWindow(el, x) {
var x = x,
width = 0,
imageDiv = el.find('.imageDiv'),
imageWrapper = el.find('.imageWrapper'),
images = el.find('.imageDiv img');
el.find('.imageDiv, .imageDiv img').css({
height: (x/160)*75+75 >= 150 ? 150 : (x/160)*75+75
});
for (var i = 0, l = images.length; i < l; i++) {
width += $(images[i]).width();
if (imageWrapper.width() >= width && i !== 0) {
$(images[i]).addClass('out').css({
left: (width-$(images[i]).outerWidth(true)) + 'px'
});
} else {
i !== 0 && $(images[i]).removeClass('out').css({
left: 0
});
}
}
if (x+images.first().width() <= width) imageWrapper.width(x+images.first().width());
imageDiv.css('right', (-$(this).width()+images.first().width()) + 'px');
}
});

If statement in setInterval only working once

I'm new to Stack Overflow, so excuse me if I'm completely doing something I shouldn't be doing, and let me know so I can learn.
Anyway! The code:
$(document).ready(function() {
var imgWidth = $(".window").width();
var imgSize = $(".image_reel img").size();
var imgReelWidth = imgWidth * imgSize;
$(".image_reel").css({
width: imgReelWidth});
var num = 960;
var numImgs = $('div.image_reel img').length;
var currentSlide = 0;
setInterval(function() {
currentSlide++;
if (currentSlide != numImgs) {
$(".image_reel").animate({
left: -num
}, 1000);
}
else {
var setWidth = numImgs - 1;
var newSlideNum = num * setWidth;
$(".image_reel").animate({
left: newSlideNum
}, 1000);
currentSlide = 0;
}
}, 2000);
});
What this code is supposed to be doing (or at least I thought it was...) is that after 2 seconds, it will loop through the if statement and check if the "current slide" is equal to the amount of images there are. Now I checked with the alert function to see if all the numbers are correct and they are, but for some reason, the slider is only working once, and that's it. Any ideas why?
Thanks in advance guys.
This might be your problem:
var numImgs = $('div.image_reel img').length;
This holds the number of images at the moment it's called, not every time you call it. Replace numImgs with $('div.image_reel img').length in your code, and see if it works:
$(document).ready(function() {
var imgWidth = $(".window").width();
var imgSize = $(".image_reel img").size();
$(".image_reel").css('width', imgWidth * imgSize);
var num = 960;
var currentSlide = 0;
var setWidth = 0;
var newSlideNum = 0;
setInterval(function() {
currentSlide++;
if (currentSlide < $('div.image_reel img').length) {
$(".image_reel").animate({left: -num}, 1000);
} else {
setWidth = numImgs - 1;
newSlideNum = num * setWidth;
$(".image_reel").animate({left: newSlideNum}, 1000);
currentSlide = 0;
}
}, 2000);
});

JS/jQuery delay loop to get desire result (delay() not working)

I'm trying to create an loading icon by moving the css 'background-position' of an image in a loop:
$('#LoginButton').click(function () {
var i = 1, h = 0, top;
for (i = 0; i <= 12; i++) {
h = i * 40;
top = h + 'px';
$('#ajaxLoading').css('background-position', '0 -' + top).delay(800);
}
});
The problem here is that it runs to fast so I don't se the 'animation' of the moving background.
So I added jquerys delay(), but:
delay(800) is not working because delay() only works in jquery animation effects and .css() is not one of those.
How to delay this loop?
I'd suggest using jQuery timer plugin: http://jquery.offput.ca/js/jquery.timers.js
$('#LoginButton').click(function () {
var times = 13;
var delay = 300;
var h = 0, top;
$(document).everyTime(delay, function(i) {
top = h + 'px';
$('#ajaxLoading').css('background-position', '0 -' + top);
h += 40;
}, times);
});
In case you don't want any plugins, use setInterva/clearInterval:
$('#LoginButton').click(function () {
var delay = 300;
var times = 13;
var i = 0, h = 0, top;
doMove = function() {
top = h + 'px';
$('#ajaxLoading').css('background-position', '0 -' + top);
h += 40;
++i;
if( i >= times ) {
clearInterval( interval ) ;
}
}
var interval = setInterval ( "doMove()", delay );
});
Have you looked at using animate() instead of css()? I'm not 100% sure I understand what you're trying to accomplish, so this is kinda a shot in the dark.
http://api.jquery.com/animate/
Chrome, Safari and IE3+ should support background-position-y, so if you're targeting these specific browser, using jquery you could just make a timed animation() on backgroundPositionY property - http://snook.ca/archives/html_and_css/background-position-x-y
(On Firefox the effect won't work)
You can use setTimeout() and clearTimeout() functions in order to accomplish that.
IE:
var GLOBAL_i = 0;
function doAnimation() {
var h = GLOBAL_i * 40;
var top = h + 'px';
$('#ajaxLoading').css('background-position', '0 -' + top);
if (GLOBAL_i < 12) {
GLOBAL_i++;
t=setTimeout(doAnimation, 800);
}
}
$('#LoginButton').click(function () {
doAnimation()
});

javascript toggle animation issue

I am doing a small javascript animation. this is my code :
window.onload = function () {
var heading = document.getElementsByTagName('h1')[0];
heading.onclick = function () {
var divHeight = 250;
var speed = 10;
var myInterval = 0;
alert(divHeight);
slide();
function slide() {
if (divHeight == 250) {
myInterval = setInterval(slideUp, 30);
} else {
myInterval = setInterval(slideDwn, 30);
alert('i am called as slide down')
}
}
function slideUp() {
var anima = document.getElementById('anima');
if (divHeight <= 0) {
divHeight = 0;
anima.style.height = '0px';
clearInterval(myInterval);
} else {
divHeight -= speed;
if (divHeight < 0) divHeight = 0;
anima.style.height = divHeight + 'px';
}
}
function slideDwn() {
var anima = document.getElementById('anima');
if (divHeight >= 250) {
divHeight = 250;
clearInterval(myInterval);
} else {
divHeight += speed;
anima.style.height = divHeight + 'px';
}
}
}
}
i am using above code for simple animation. i need to get the result 250 on the first click, as well second click i has to get 0 value. but it showing the 250 with unchanged. but i am assigning the value to set '0', once the div height reached to '0'.
what is the issue with my code? any one help me?
Everytime you click on the div the divHeight variable is reset to 250, thus your code never calls slideDwn. Moving the divHeight declaration outside the event handler should do the trick.
Also, your div wont have the correct size when any of the 2 animations end. You're setting the divHeight variable to 250 or 0 correctly, but never actually setting anima.style.height after that.
I've rewritten your code into something simpler and lighter. The main difference here is that we're using a single slide() function here, and that the height of the div in question is stored in a variable beforehand to ensure that the element slides into the correct position.
Note that this is a very simplistic implementation and assumes that the div carries no padding. (The code uses ele.clientHeight and ele.style.height interchangeably, which admittedly, is a pretty bad choice, but is done here to keep the code simple)
var heading = document.getElementsByTagName('h1')[0],
anima = document.getElementById('anima'),
divHeight = anima.clientHeight,
speed = 10,
myInterval = 0,
animating = false;
function slide(speed, goal) {
if(Math.abs(anima.clientHeight - goal) <= speed){
anima.style.height = goal + 'px';
animating = false;
clearInterval(myInterval);
} else if(anima.clientHeight - goal > 0){
anima.style.height = (anima.clientHeight - speed) + 'px';
} else {
anima.style.height = (anima.clientHeight + speed) + 'px';
}
}
heading.onclick = function() {
if(!animating) {
animating = true;
var goal = (anima.clientHeight >= divHeight) ? 0 : divHeight;
myInterval = setInterval(slide, 13, speed, goal);
}
}
See http://www.jsfiddle.net/yijiang/dWJgG/2/ for a simple demo.
I've corrected your code a bit (See working demo)
window.onload = function () {
var heading = document.getElementsByTagName('h1')[0];
var anima = document.getElementById('anima');
var divHeight = 250;
heading.onclick = function () {
var speed = 10;
var myInterval = 0;
function slideUp() {
divHeight -= speed;
if (divHeight <= 0) {
divHeight = 0;
clearInterval(myInterval);
}
anima.style.height = divHeight + 'px';
}
function slideDwn() {
divHeight += speed;
if (divHeight >= 250) {
divHeight = 250;
clearInterval(myInterval);
}
anima.style.height = divHeight + 'px';
}
function slide() {
console.log(divHeight )
if (divHeight == 250) {
myInterval = setInterval(slideUp, 30);
} else {
myInterval = setInterval(slideDwn, 30);
}
}
slide();
}
}​

Categories