Why is it looping through the 'else' in my if/else statement? - javascript

If you enable the alert(rand) at the bottom of my if/else statement, you will notice that when ran, it will constantly loop over the else section of my if/else statement. It's probably a simple fix, but I can't seem to figure it out. I had it working in the earlier stages of development but can't seem to figure it out now.
I'll post the code below, but it's probably easier to look at my jsfiddle, here: http://jsfiddle.net/zAPsY/7/ Thanks.
$(document).ready(function(){
//You can edit the following file paths to change images in selection
var img1 = '<img src="images/luke.jpg">';
var img2 = '<img src="images/luke.jpg">';
var img3 = '<img src="images/luke.jpg">';
var img4 = '<img src="images/luke.jpg">';
var img5 = '<img src="images/luke.jpg">';
var img6 = '<img src="images/luke.jpg">';
var all = img1 + img2 + img3 + img4 + img5 + img6;
//Rotation
var speed = 0.00;
var radius = 80;
var count = 0;
$("#run").bind("click",runButtonClick);
function rotate()
{
var centerx = $(document).width()/2;
var centery = $(document).height()/2;
var num_items = $("#container > img").length;
$("#container > img").each(function(){
var angle = count * (Math.PI/180);
var newx = centerx + Math.cos(angle)*radius - $(this).width()/2;
var newy = centery + Math.sin(angle)*radius - $(this).height()/2;
$(this).css("left",newx+"px").css("top",newy+"px");
count += 360/num_items + speed;
});
}
setInterval(rotate,100/1000);
//Append elements to container
$("#appendall").click(function(){$('#container').append(all);});
$('#append').children().eq(2).click(function(){$('#container').append(img1);});
$('#append').children().eq(3).click(function(){$('#container').append(img2);});
$('#append').children().eq(4).click(function(){$('#container').append(img3);});
$('#append').children().eq(5).click(function(){$('#container').append(img4);});
$('#append').children().eq(6).click(function(){$('#container').append(img5);});
$('#append').children().eq(7).click(function(){$('#container').append(img6);});
//Refresh page
$("#reset").click(function(){location.reload();});
//IF speed is greater than 0 - ELSE add animation to div element
function runButtonClick() {
var maxcount = 0.40;
var incdec = 0.01;
setInterval(function(){counter();}, 100);
counter()
speed;
function counter()
{
if (maxcount >= 0.00)
{
maxcount = maxcount - incdec;
speed = speed + incdec;
//alert(speed)
//alert(maxcount)
}
else if (maxcount <= 0.00)
{
speed = 0.00;
//Find amount of div elements and add 1
var brewees = $('#container').children().length +=1;
//get a random number
var rand = (Math.floor(Math.random()*brewees));
var ap = '20px';
var ab = '#ddd';
var ad = 1000;
//match random number corrosponding child in div
$('#container').children().eq(parseFloat(rand))
.animate({padding: ap, background : ab}, {duration:ad});
alert(rand);
}
}
}
});

You let your maxcount drop below zero but still your function is being called every 100ms (due to your setInterval).
So you should clear that interval eventually by doing:
/* first */
var intervalID = setInterval(function(){counter();}, 100);
/* later */
clearInterval(intervalID);

You're calling the function at a rate of 10 times per second (setInterval). Eventually, the maxcount variable will drop below 0, causing the else condition to execute.
You should store the interval call in a variable, and use clearInterval at else, so that the function runs only once after else:
//Store a reference to the interval
var interval = setInterval(function(){counter();}, 100);
...
function counter(){
...
else if(..){
...
clearInterval(interval); //Clear the previously defined interval
}
...
Another note: In the code, speed; has no use. Either prefix it by var (var speed;), or remove it.

Related

I have some JavaScript function that keeps repeating itself, I can't find why

This is code that generates a selected image when a function is run, but the image keeps changing, I want this code to let me have one image and keep it that way instead of it changing randomly every 0.5 - 3 seconds, and I don't know why!
const imageSelector = document.querySelector("#changeHeron")
function spinMachine() {
document.getElementById('spinner').disabled = 'disabled';
spinner.style.transform = "rotate(90deg)";
setInterval(enterBall, 1000)
var protmt = prompt("What's your name?")
alert("Hey there " + protmt + ", " + "its great to see you here")
}
function enterBall() {
var ball = document.getElementById("changeHeron");
ball.style.opacity = "100%";
ball.style.transform = "ScaleX(50%) ScaleY(50%)";
setInterval(liftBall, 1000);
}
function liftBall() {
var ball = document.getElementById("changeHeron");
ball.style.transform = "translateY(-250%)";
ball.style.transform = "ScaleX(200%) ScaleY(200%)";
ball.style.top = "40%";
setInterval(changeImage, 1500);
}
function changeImage() {
var images = ["./Images/Football.png", "./Images/Mousetache.png", "./Images/OG.svg"];
var randomNum = Math.floor(Math.random() * images.length);
var ball = document.getElementById("changeHeron");
ball.src = images[randomNum];
ball.style.borderRadius = "5%";
ball.style.backgroundColor = "white";
}
I found that you can place the images varible outside and change it inside when the code has ran so that the rest can just work outside of this problem

Javascript help, Trying to animate two different sprites at same time

I need some javascript help. I am trying to set up two sprite animations with different frame rates in two separate div.
Here is a fiddle I started and i am very much stuck.
How do I combine the two div IDs into one statement? OR Should I be using ClassName in the statement to run on both divs?
http://jsfiddle.net/akwilinski/3t7d6qbL/1/
<div id="animate" class="animation"></div>
<div id="animate2" class="animation2"></div>
onload = function startAnimation() {
var frameHeight = 400;
var frames = 27;
var frame = 0;
var div = document.getElementById("animate");
setInterval(function () {
var frameOffset = (++frame % frames) * -frameHeight;
div.style.backgroundPosition = "0px " + frameOffset + "px";
}, 100);
}
Thank you for any assistance!
Simplest way to do this using the method you have already started using is to define 2 new variables, 1 for the second div and one for the second frame count. Then you can just add the call to your function.
Updated js:
onload = function startAnimation() {
var frameHeight = 400;
var frames = 27;
var frame = 0;
var div = document.getElementById("animate");
var div2 = document.getElementById("animate2");
setInterval(function () {
var frameOffset = (++frame % frames) * -frameHeight;
var frameOffset2 = (++frame % frames) * -frameHeight - 10;
div.style.backgroundPosition = "0px " + frameOffset + "px";
div2.style.backgroundPosition = "0px " + frameOffset + "px";
}, 100);
}
Fiddle
http://jsfiddle.net/f4v1vy7x/5/
I made a Can object to store the configuration for each can (so you can have different frameHeights, frames and frameRates.
I used window.requestAnimationFrame because it's far more efficient than setInterval. On each available frame I check whether it's time to animate based on each Can's set frame rate:
var Can = function( selector, frameHeight, frames, frameRate )
{
this.domCan = document.getElementById( selector );
this.frameHeight = frameHeight;
this.frames = frames;
this.frameRate = frameRate;
this.frame = 0;
};
onload = function startAnimation() {
var can1 = new Can( 'animate', 400, 27, 20 );
var can2 = new Can( 'animate2', 400, 27, 100 );
var cans = [ can1, can2 ];
window.requestAnimationFrame( function() {
can1.start = can2.start = new Date();
animate( cans );
} );
};
var animate = function( cans ) {
for( var i = 0; i < cans.length; i++ ) {
var now = new Date();
var can = cans[i];
if( now - can.start >= 1000 / can.frameRate ) {
can.start = now;
var frameOffset = (++can.frame % can.frames) * -can.frameHeight;
can.domCan.style.backgroundPosition = "0px " + frameOffset + "px";
}
}
window.requestAnimationFrame( function() {
animate( cans );
} );
}
You could do something like this:
var div = document.getElementById("animate");
var div2 = document.getElementById("animate2");
function anim(div) {
setInterval(function () {
var frameOffset = (++frame % frames) * -frameHeight;
div.style.backgroundPosition = "0px " + frameOffset + "px";
}, 100);
}
anim(div);
anim(div2);
You could then pass in additional parameters like frameHeight, frame, and frames to further customize each animation.

Modifying a simple jquery game

I am trying to modify this game, right now it shows 9 images at random positions and the user has to click on them and when it reaches 10 clicks the game ends. I want to appear only one image. I will share the original function and the function I have modified it.
Original
function createImages(){
var myarray= ["img/img1.gif","img/img2.gif","img/img3.png",
"img/img4.gif","img/img5.gif","img/img6.gif",
"img/img7.gif","img/img8.png", "img/img9.jpg"];
var count=0;
var div;
for (var i = 0; i < 9; i++) {
var randPos = 0 + Math.floor(Math.random() * 500);
this.img = document.createElement("img");
div = document.createElement("div");
$("div").attr("id","div"+i);
var randNew = 0 + Math.floor(Math.random() * (5));
var rand = 0 + Math.floor(Math.random() * (9-count));
this.img.src = myarray[rand];
$('#div'+i).css("left", randPosition());
$('#div'+i).css("right", randPosition());
$('#div'+i).css("top", randPosition());
$('#div'+i).css("bottom",randPosition());
$('#div'+i).css("position","relative");
$('#div'+i).show();
div.appendChild(this.img);
$("body").prepend(div);
myarray.splice(rand,1);
count++;
}
}
After I modified it
function createImages(){
var count=0;
var div;
for (var i = 0; i < 9; i++) {
var randPos = 0 + Math.floor(Math.random() * 500);
this.img = document.createElement("img");
div = document.createElement("div");
$("div").attr("id","div");
var randNew = 0 + Math.floor(Math.random() * (5));
var rand = 0 + Math.floor(Math.random() * (9-count));
this.img.src = "img/img1.gif";
$('#div').css("left", randPosition());
$('#div').css("right", randPosition());
$('#div').css("top", randPosition());
$('#div').css("bottom",randPosition());
$('#div').css("position","relative");
$('#div').show();
div.appendChild(this.img);
$("body").prepend(div);
count++;
}
}
The problem is that now it appears the same image 10 times, I want it to appear only once and then disappear and appear again. Can anyone help me fix this issue.
If it's not to much to ask I would like to put this image inside a div so it wouldn't appear all over the page.
function randPosition() {
return 0 + Math.floor(Math.random() * 500);
}
In createImages() function you have a loop that adds the image 10 times:
for (var i = 0; i < 9; i++) {
...
}
Remove it, and it'll do it only once. Also you can simplify the code removing some random variables that are not used.
Further, this two sentences aren't correct. The first one creates a div in a variable named also div. The second is selector for all div elements, you are not referencing the new created one as I think you expect.
div = document.createElement("div");
$("div").attr("id","div");
You should create a jQuery object with the new created div to work with it:
var div = document.createElement("div");
$div = $(div); // << Create jQuery object wrapping the new div
$div.css("left", randPosition());
Edited function:
function createImages(){
var div = document.createElement("div");
$div = $(div);
$div.css("left", randPosition());
$div.css("right", randPosition());
$div.css("top", randPosition());
$div.css("bottom",randPosition());
$div.css("position","relative");
$div.show();
var img = document.createElement("img");
img.src = "http://dummyimage.com/25x25/4F4/000.png";
div.appendChild(img);
$("body").prepend(div);
}
EDIT: I've built a JSFiddle for you so you can play with it: http://jsfiddle.net/6aLh9qam/3/

javascript rotator / no jQuery

I am working on a slider to rotate/fade Divs without using jQuery.
This is what I got so far: http://jsfiddle.net/AlexHuber/V2Avd/24/
It rotates once through the array of 4 Divs, continues to the first Div and then stops.
Any ideas? Thanks, Alex
var box=document.getElementById("box");
var index=box.children.length-1;
var active;
var next;
box.children[0].style.zIndex="1";
box.children[1].style.zIndex="1";
box.children[2].style.zIndex="1";
box.children[3].style.zIndex="1";
var timer1 = setInterval(function(){
active = box.children[index];
next = (index > 0) ? box.children[index-1] : box.children[box.children.length-1];
active.style.zIndex = "3";
next.style.zIndex = "2";
var opa = 1.0;
var timer2 = setInterval(function(){
if (opa <= 0){
active.style.zIndex="1";
active.style.opacity="1.0";
next.style.zIndex="3";
clearInterval(timer2);
}
else {
active.style.opacity = opa;
opa -= 0.1;
}
}, 50);
index -= 1;
if (index < 0)
index = box.children.lenght-1;
}, 2000);
On your second from last line change .lenght-1 to .length-1
that makes the divs rotate indefinitely. I'm assuming that's what you want.

How to add scroll background effect to multiple elements with different settings?

In this demo http://www.htmldrive.net/items/demo/527/Animated-background-image-with-jQuery
This code is for one background only. I want to add multiple background with different direction and speed.
var scrollSpeed = 70;
var step = 1;
var current = 0;
var imageWidth = 2247;
var headerWidth = 800;
var restartPosition = -(imageWidth - headerWidth);
function scrollBg(){
current -= step;
if (current == restartPosition){
current = 0;
}
$('#header').css("background-position",current+"px 0");
}
var init = setInterval("scrollBg()", scrollSpeed);
Currently it has settings for
$('#header').css("background-position",current+"px 0");
In a website I want to use this effect on #footer or #content background also. but with different speed and direction.
And is there any better and more optimized jquery method to achieve same effect?
And can we get same effect using CSS 3, without javascript?
Just saw the OP's answer, but decided to post anyway:
I've created a jQuery plugin to do this:
(function($) {
$.fn.scrollingBackground = function(options) {
// settings and defaults.
var settings = options || {};
var speed = settings.speed || 1;
var step = settings.step || 1;
var direction = settings.direction || 'rtl';
var animStep;
// build up a string to pass to animate:
if (direction === 'rtl') {
animStep = "-=" + step + "px";
}
else if (direction === 'ltr') {
animStep = '+=' + step + "px";
}
var element = this;
// perform the animation forever:
var animate = function() {
element.animate({
backgroundPosition: animStep + " 0px"
}, speed, animate);
};
animate();
};
})(jQuery);
Usage:
$("#header").scrollingBackground({
speed: 50,
step: 50,
direction: 'ltr'
});
This is pretty basic, and assumes that you're background-repeat is 'repeat-x' on the element you call it on. This way, there's no need to reset the background position every so often.
Working example: http://jsfiddle.net/andrewwhitaker/xmtpr/
I could work out the following solution. Am not sure if it is efficient. Will wait for anyone to comment or provide a better option.
Till then...:
var scrollSpeed = 70;
var step = 1;
var current = 0;
var images =
[
{
imageWidth:2247,
imagePath:"images/image1"
},
{
imageWidth:1200,
imagePath:"images/image2"
}
]
var headerWidth = 800;
var imageRotateCount = 0;
var imagesLength = images.length;
$('#header').css("background-image", images[0].imagePath);
function scrollBg(){
var curIndex = imageRotateCount%imagesLength;
var curImage = images[curIndex];
current -= step;
var restartPosition = -(curImage.imageWidth - headerWidth);
if (current == restartPosition){
current = 0;
imageRotateCount++;
curIndex = imageRotateCount%imagesLength;
curImage = images[curIndex];
$('#header').css("background-image", curImage.imagePath);
}
$('#header').css("background-position",current+"px 0");
}
var init = setInterval("scrollBg()", scrollSpeed);

Categories

Resources