If statement in setInterval only working once - javascript

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

Related

jQuery slider doesn't stop on mouseover

My jQuery slider is working but I don't know why it doesn't stop when I hover it.
I'm not using any slider plugin for this.
Here is the code.
$(function(){
var width = 720;
var animationSpeed = 1000;
var pause = 3000;
var currentSlide = 1;
var $slider= $('#slider');
var $slideContainer = $slider.find('.slides');
var $slides = $slideContainer.find('.slide');
var interval;
function startSlider(){
setInterval(function(){
$slideContainer.animate({'margin-left': '-='+width}, animationSpeed, function(){
currentSlide++;
if(currentSlide === $slides.length){
currentSlide = 1;
$slideContainer.css('margin-left', 0);
}
});
}, pause);
}
function stopSlider(){
clearInterval(interval);
}
$slider.on('mouseenter', stopSlider).on('mouseleave', startSlider);
startSlider();
stopSlider();
});
Any help would be appreciated.
Try this ;)
var width = 720;
var animationSpeed = 1000;
var pause = 3000;
var currentSlide = 1;
var interval;
var $slider = "";
var $slideContainer = "";
var $slides = "";
function startSlider(){
interval = setInterval(function(){
$slideContainer.animate({
'margin-left': '-=' + width
},
animationSpeed, function(){
currentSlide++;
if(currentSlide === $slides.length){
currentSlide = 1;
$slideContainer.css('margin-left', 0);
}
});
}, pause);
}
function stopSlider(){
clearInterval(interval);
}
$(function(){
$slider = $('#slider');
$slideContainer = $slider.find('.slides');
$slides = $slideContainer.find('.slide');
$slider.on('mouseenter', stopSlider).on('mouseleave', startSlider);
startSlider();
});
Man you do it wrong.
To stop an interval you need to assign it to a variable before.
Create your interval and assign it to var:
var timer = setInterval(function (){
// do stuff here
});
You have your time setted up, now you can stop it! Like this:
clearInterval(timer);
Hope to help you :)
if you want to Stop the interval you need to do it like:
var interval = setInterval(function(){//do stuff here});
clearInterval(interval);
Just remove $ from your variable prefix, it is not php, it is jquery.

Using jQuery to switch background position every 250px

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

Javascript - setInterval for 2 auto slide on the same page

I was trying to create a auto slide for the slider using setInterval. It works like a charm when there's only one slider.
When there are 2 slider, the first slider wont work, and the second slider will slide faster, because there will be 2 setInterval and both are sliding the second slider. Anyway to make sure each setInterval slide their own slider?
var autoSlideTimer = 5;
var autoslide = setInterval(function () {
if (autoSlideTimer == 0) {
var slideMargin = offsetMarginLeft - width;
if (-slideMargin == (width * totalImages)) {
offsetMarginLeft = width;
displayImage = 0;
}
slider.style.marginLeft = (offsetMarginLeft - width) + 'px';
displayImage += 1;
pagination = element.getElementsByTagName('ul')[0];
pagination.innerHTML = paginate;
pagination.getElementsByTagName('li')[displayImage - 1].setAttribute("class", "displayed");
slider = element.getElementsByTagName('div')[0];
offsetMarginLeft = parseInt(slider.style.marginLeft.replace('px', ''));
autoSlideTimer = 5;
} else {
autoSlideTimer--;
}
}, 1000);
thanks
I work it out with another way, although is working but doesnt seems to be the perfect way
var event = new Event('build');
// Listen for the event.
element.addEventListener('build', function (e) {
function timeoutLoop()
{
setTimeout(function(){
if(autoSlideTimer == 0)
{
var slideMargin = offsetMarginLeft - width;
if(-slideMargin == (width * totalImages))
{
offsetMarginLeft = width;
displayImage = 0;
}
slider.style.marginLeft = (offsetMarginLeft - width) + 'px';
displayImage += 1;
pagination = element.getElementsByTagName('ul')[0];
pagination.innerHTML = paginate;
pagination.getElementsByTagName('li')[displayImage - 1].setAttribute("class", "displayed");
offsetMarginLeft = parseInt(slider.style.marginLeft.replace('px', ''));
autoSlideTimer = 5;
}else
{
autoSlideTimer--;
}
timeoutLoop();
},1000);
}
timeoutLoop();
}, false);
// Dispatch the event.
element.dispatchEvent(event);
At first, I used setInterval inside, yet the slider will be overwritten. But setTimeout is ok.

javascript, slide div down on button click?

i am trying to get a div to slide down about 200px down a page using javascript when the user clicks another div which acts as a close button.
can someone please show me how i would do this?
<script>
$('.chat_close').click(function(e){
$('.chat_box').slideDown();
});
</script>
Someone already asked the same question a while ago. Avinash replied:
var minheight = 20;
var maxheight = 100;
var time = 1000;
var timer = null;
var toggled = false;
window.onload = function() {
var controler = document.getElementById('slide');
var slider = document.getElementById('slider');
slider.style.height = minheight + 'px'; //not so imp,just for my example
controler.onclick = function() {
clearInterval(timer);
var instanceheight = parseInt(slider.style.height); // Current height
var init = (new Date()).getTime(); //start time
var height = (toggled = !toggled) ? maxheight: minheight; //if toggled
var disp = height - parseInt(slider.style.height);
timer = setInterval(function() {
var instance = (new Date()).getTime() - init; //animating time
if(instance <= time ) { //0 -> time seconds
var pos = instanceheight + Math.floor(disp * instance / time);
slider.style.height = pos + 'px';
}else {
slider.style.height = height + 'px'; //safety side ^^
clearInterval(timer);
}
},1);
};
};
You can see it here at this URL:
http://jsbin.com/azewi5
Use animate
Also, use .on
<script type="text/javascript">
$('.chat_close').on('click', function(e){
$('.chat_box').animate({"top": "200px");
});
</script>
HTML:
<div class="chat_close">
</div>

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