Javascript is timeout in loop valid - javascript

I am trying to build a visual sorting algorithm. I search through the data and whenever I find a new min I add the selected class. The algorithm works but it shows all the new mins at once and not one at a time. I tried to achieve one by one with setTimeout but this did not work. Is the usage of setTimeout invalid?
Thank you
var gBars = [];
function Bar(index, height){
this.index = index;
this.height = height;
this.getIndex = function(){
console.log(this.index);
};
this.getHeight = function(){
console.log(this.height);
};
this.getStats = function(){
console.log(this.index + ' ' + this.height);
}
this.setHeight = function(h){
this.height = h;
}
this.setIndex = function(i){
this.index = i;
}
}
function insertAfter(newNode, referenceNode){
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
function setHeight(i, h){
document.getElementById(i).style.height = h + 'em';
}
function addBar(i, h){
//base case i = 0
//first bar
if(i === 0){
var currentDiv = document.getElementById("root");
d = document.createElement('div');
d.setAttribute("id", 'block'+i);
d.setAttribute("class", 'block');
gBars[i] = new Bar(i, h);
currentDiv.appendChild(d);
setHeight('block'+i,h);
}
else {
let last = i-1;
var currentDiv = document.getElementById('block'+last);
d = document.createElement('div');
d.setAttribute("id", 'block'+i);
d.setAttribute("class", 'block');
gBars[i] = new Bar(i, h);
insertAfter(d, currentDiv);
setHeight('block'+i,h);
}
}
function findMin() {
let min = gBars[19].height;
//start at 18 because bars are rotated 180deg
//go backwards so it appears to go forwards
var delay = 500;
for(let i=18; i>=0; i--) {
setTimeout(function() {
if(min > gBars[i].height) {
min = gBars[i].height;
var selected = document.getElementById('block'+i);
selected.style.backgroundColor = "blue";
console.log('new min ' + min);
}
}, delay);
}
return min;
}
function init(){
for(let i=0; i<20; i++){
let ran = Math.floor(Math.random() * 50 + 1);
gBars[i] = new Bar(i,ran);
addBar(i,ran);
}
for(let i=0; i<20; i++){
gBars[i].getStats();
}
let min = findMin();
console.log('min '+ min);
}
init();
.selected{
background-color:blue;
}
.block{
border:1px solid rgba(0,0,0,.4);
width:20px;
background-color:grey;
}
#root{
display:flex;
transform:rotate(180deg);
position:absolute;
left:10%;
}
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<button>sort</button>
<div id="root"></div>
</body>
<script src="selectionsort.js"></script>
</html>

the best way to solve your problem is to create recursive function. It will fire itself after specified delay and once more after delay and once more until you will stop it.
Here, have some code:
function findMin() {
let min = gBars[19].height;
//start at 18 because bars are rotated 180deg
//go backwards so it appears to go forwards
var delay = 500;
let i = 18
min = setTimeout(timeout(i, min), delay);
return min;
}
function timeout(i, min) {
console.log("Next loop: " + i);
if(min > gBars[i].height) {
min = gBars[i].height;
var selected = document.getElementById('block'+i);
selected.style.backgroundColor = "blue";
console.log('new min ' + min);
}
i--;
if (i == 0) {
console.log("End");
return min;
} else {
setTimeout(function(){
return timeout(i, min);
},500)
}
}
You can see how it will run only after the previous function has been fired, so after the delay you have set.

Related

Increase and decrease SVG shape - JS

I would like you to help me for a thing here, for a function to increase and then decrease SVG shape when it hits limit.
It should go from 3 to 6 and then 6 to 3 and so on... but instead it goes from 3 to 6 and then 6 to minus infinite. And I don't understand why.
Here is my code :
var size = 3;
var sizeManager = 1;
function increaseAnimation(el){
var elem = document.getElementById(el);
elem.style.transform = "scale("+size+")";
timer = setTimeout('increaseAnimation(\''+el+'\',3000)');
size=size+0.005*sizeManager;
if(size >= 6){
sizeManager=sizeManager*-1;
}
if (size <= 3){
sizeManager=sizeManager*+1;
}
}
Your weird setTimeout implementation, with bound was broken.
There's also the issue that your sizeManager is not properly reflecting:
function increaseAnimation(id, interval) {
var size = 1;
var velocity = 0.05;
var elem = document.getElementById(id);
function iterate() {
elem.style.transform = "scale(" + size + ")";
size += velocity;
if (size > 2 || size < 1) {
velocity *= -1; // velocity reflected
}
}
var timer = setInterval(iterate, interval);
return function stop() {
clearInterval(timer)
}
}
I also added a stop function which you can call at a later point.
var stopper = increaseAnimation("content", 16);
setTimeout(stopper, 5000);
The error is with the line sizeManager=sizeManager*+1; Multiplying a number by one doesn't change it. You basically want to toggle sizeManager between -1 and +1, and you can do so by multiplying by -1, regardless of whether it is currently negative or positive.
I've tested this code and it seems to work:
var size = 3;
var sizeManager = 1;
function increaseAnimation(el) {
var elem = document.getElementById(el);
elem.style.transform = "scale(" + size + ")";
timer = setTimeout("increaseAnimation('" + el + "', 3000)");
size += 0.005 * sizeManager;
if (size >= 6 || size <= 3) {
sizeManager *= -1;
}
}
Full HTML for a POC demo at: https://pastebin.com/GW0Ncr9A
Holler, if you have questions.
function Scaler(elementId, minScale, maxScale, deltaScale, direction, deltaMsecs) {
var scale = (1 == direction)?minScale:maxScale;
var timer = null;
function incrementScale() {
var s = scale + deltaScale*direction;
if (s < minScale || s > maxScale) direction *= -1;
return scale += deltaScale*direction;
};
function doScale(s) {
document.getElementById(elementId).style.transform = 'scale(' + s + ')';
};
this.getDeltaMsecs = function() {return deltaMsecs;};
this.setTimer = function(t) {timer = t;};
this.run = function() {doScale(incrementScale());};
this.stop = function() {
clearInterval(timer);
this.setTimer(null);
};
};
var scaler = new Scaler('avatar', 3, 6, .05, 1, 50);
function toggleScaler(ref) {
if ('run scaler' == ref.value) {
ref.value = 'stop scaler';
scaler.setTimer(setInterval('scaler.run()', scaler.getDeltaMsecs()));
}
else {
scaler.stop();
ref.value = 'run scaler';
}
};

I need to make a countdown of where the images show up and move in random directions. I could only use Javascript

So I have to make a countdown of where the images show up and they slide in random directions. I have gotten the countdown to work, but the shapes do not move. I could only use Javascript, no JQuery. Here is my code so far:
https://jsfiddle.net/IyamSIM/L6umLkt8/
function countdown() {
var seconds;
var way;
seconds = document.getElementById('countdown').innerHTML;
seconds = parseInt(seconds, 10);
if (seconds == 1) {
way = document.getElementById('countdown');
way.innerHTML = "End";
ham();
sis();
wash();
return;
}
seconds--;
way = document.getElementById('countdown');
way.innerHTML = seconds;
timeoutMyStop = setTimeout(countdown, 100);
}
countdown();
function ham() {
var elem = document.getElementById("ham");
var pos = 0;
var id = setInterval(frame, 8);
function frame() {
if (pos == 550) {} else {
pos++;
elem.style.bottom = pos + 'px';
elem.style.left = pos + 'px';
}
}
}
function sis() {
var elem = document.getElementById("sis");
var pos = 0;
var id = setInterval(frame, 8);
function frame() {
if (pos == 250) {} else {
pos++;
elem.style.left = pos + 'px';
}
}
}
function wash() {
var elem = document.getElementById("wash");
var pos = 0;
var id = setInterval(frame, 8);
function frame() {
if (pos == 290) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + 'px';
elem.style.left = pos + 'px';
}
}
}
img{
width: 100px;
height: 100px;
}
<body>
<h1>Countdown Surprise Assignment</h1>
<center><div id="countdown">10</div></center>
<img id ="ham" src="https://simranjits-swamped-story.neocities.org/FINAL_PROJECT/hamilton.jpg">
<img id ="sis" src="https://simranjits-swamped-story.neocities.org/FINAL_PROJECT/sisters.jpg">
<img id ="sis" src="https://simranjits-swamped-story.neocities.org/FINAL_PROJECT/washington.jpg">
You could let CSS3 do the job for you.
Also why don't you create a random function generator? That's what you need after all, the one below will generate a number given a min and max value range.
var EL_countdown = document.getElementById('countdown'),
ELs_card = document.getElementsByClassName('card'),
sec = 10;
// random generator
function rnd(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
function countdown() {
sec--;
EL_countdown.innerHTML = !sec ? "End" : sec;
if (!sec) return flyTime();
else setTimeout(countdown, 100);
}
// Assign a random transition-timing and translate(x, y) position
function flyTime() {
// assign CSS3 transition and transform to every card
for (var i = 0; i < ELs_card.length; i++) {
ELs_card[i].style.transition = rnd(1, 6) + "s";
ELs_card[i].style.transform = "translate(" + rnd(20, 250) + "px, " + rnd(30, 120) + "px)";
}
}
countdown();
<div id="countdown">-</div>
<img class="card" src="//placehold.it/50x50/0bf">
<img class="card" src="//placehold.it/50x50/f0b">
<img class="card" src="//placehold.it/50x50/fb0">

Why won't this clearInterval work?

I'm making a race where two images move to the right a random number of px's but they won't stop with the clear interval, the alert "stop" works. I'm using a red and green picture with changing z-indexes like a stoplight for the user to start and stop the race.
<script type="text/javascript">
var ship = 0;
var ufo = 0;
function random()
{
var rand = Math.floor((Math.random() * 15) + 1);
var rand2 = Math.floor((Math.random() * 15) + 1);
ship = ship + rand;
ufo = ufo + rand2;
document.getElementById("ufo").style.left = ufo + 'px';
document.getElementById("spaceship").style.left = ship + 'px';
}
function start()
{
if(document.getElementById("red").style.zIndex == 1)
{
document.getElementById("red").style.zIndex = "0";
alert("go");
var timer = setInterval(function() {random()},1000);
}
else
{
document.getElementById("green").style.zIndex = "0";
document.getElementById("red").style.zIndex = "1";
clearInterval(timer);
alert("stop");
}
}
</script>
Because var timer only exists within the if statement. You need to move it outside of the start() function, like this:
var timer;
function start()
{
if(document.getElementById("red").style.zIndex == 1)
{
document.getElementById("red").style.zIndex = "0";
alert("go");
timer = setInterval(function() {random()},1000);
}
else
{
document.getElementById("green").style.zIndex = "0";
document.getElementById("red").style.zIndex = "1";
clearInterval(timer);
alert("stop");
}
}

I'm using the same js file for two different types of images named as colored and type but it isn't working for me

My problem is that I'm using the same js file with different name. The function of both files is the same. The first js file is sliding the 5 images (black and white) and the other js is sliding only two images (colored) on different links on the same page.
But both are not working properly means if one slider for black and white image is working then the other one for colored images is not working. please help me.
Js is referenced in a script file named as: coverflow-color.js
var min = 1; //minimum number of image
var max = 3; //maximum number of images
var current = 2; //image number that is at the center of the coverflow
var currPos = 0; //custom attribute that stores current TranslateX position of each image
var newPos = 0; //custom attribute that stores new TranslateX position of each image, i.e after movement
var currAngle = 0; //custom attribute that stores current RotationY angle of each image
var newAngle = 0; //custom attribute that stores new RotationY angle of each image
var gap = 75;
var clickedIndex = 0; //index of the image tapped
var isMouseDown = false; //has the user interacted
var swipeStartX = 0;
var swipeDistanceX = 0;
var diff = 0;
var imageTapStartX = 0;
var imageTapEndX = 0;
var imageTapDistanceX= 0;
var coverFlowContainerElement = null;
var thresholdDistanceSingleSlide = 0; //this measures the distance
window.addEventListener("load",function(){
/* Hide the browser address bar. This will give a native feel to the app */
setTimeout(function() { window.scrollTo(0, 1); }, 20);
/* Get the pointer to the coverflow holder */
coverFlowContainerElement = document.getElementById("coverflow");
moveImagesFromRight(); //help comments are there in the function definition
addEventsToImageHolders(); //help comments are there in the function definition
addEventToCoverflowHolder(); //help comments are there in the function definition
thresholdDistanceSingleSlide = parseInt(300 / max);
disablePageScroll(); //help comments are there in the function definition
},false);
/*
Give the initial thrust to the slides from the right. I have just given it an effect of the images being
thrown into the center from the right.
*/
function moveImagesFromRight()
{
setTimeout(function() {
document.getElementById("fig1").style.webkitTransform = "translateX(-150px) rotateY(30deg)";
document.getElementById("fig2").style.webkitTransform = "translateX(0px) rotateY(0deg) translateZ(200px)";
document.getElementById("fig3").style.webkitTransform = "translateX(150px) rotateY(-30deg)";
}, 150);
}
/* Register touch event listener to the image holders i.e the <div> holding each images */
function addEventsToImageHolders()
{
var imageHolders = coverFlowContainerElement.getElementsByTagName("div");
for(var i=0;i<imageHolders.length;i++)
{
//console.log(imageHolders[i]);
imageHolders[i].addEventListener("touchstart",handleImageTapStart,false);
imageHolders[i].addEventListener("touchend",handleImageTapEnd,false);
}
}
/*
Add touch events to the <div id='coverflow' /> container. So the container registers the finger movements
and acts accordingly
*/
function addEventToCoverflowHolder()
{
coverFlowContainerElement.addEventListener("touchstart", handleFingerSwipeStart, false);
coverFlowContainerElement.addEventListener("touchmove", handleFingerSwipeMove, false);
coverFlowContainerElement.addEventListener("touchend", handleFingerSwipeEnd, false);
}
/* The default behavior of the browser is to scroll when you swipe. This line is to prevent scrolling */
function disablePageScroll() {
document.ontouchmove = function(event) {
event.preventDefault();
}
}
/* Events for the <div id='coverflow'></div> holder */
function handleFingerSwipeStart(event) {
isMouseDown = true;
swipeStartX = event.changedTouches[0].pageX;
event.preventDefault();
}
function handleFingerSwipeMove(event) {
if (isMouseDown) {
swipeDistanceX = parseInt(event.changedTouches[0].pageX - swipeStartX);//
var netDistance = Math.abs(swipeDistanceX);
//console.log("Move: " + swipeDistanceX + " Net distance: " + netDistance); //changedTouches[0].
if (netDistance >= thresholdDistanceSingleSlide) {
//console.log(thresholdDistanceSingleSlide + " covered");
if (swipeDistanceX < 0) {
right();
swipeStartX = event.changedTouches[0].pageX;
}
else {
left();
swipeStartX = event.changedTouches[0].pageX;
}
}
}
}
function handleFingerSwipeEnd(event) {
if (isMouseDown) {
isMouseDown = false;
swipeStartX = 0;
}
}
/*
Events for the <div id="fig"></div> elements where fig starts from 1 to 7. The images are
inside these element
*/
function handleImageTapStart(event) {
imageTapStartX = event.changedTouches[0].pageX;
}
function handleImageTapEnd(event) {
imageTapEndX = event.changedTouches[0].pageX;
imageTapDistanceX = imageTapEndX - imageTapStartX;
var targetObj = event.currentTarget;
if (imageTapDistanceX == 0) {
clickedIndex = parseInt(targetObj.id.slice(3, 4));
if (clickedIndex > current) {
//move right to the clicked index
diff = clickedIndex - current;
for (var i = 1; i <= diff; i++) {
right();
}
}
else if (clickedIndex < current) {
//move left to the clicked index
diff = (current - clickedIndex);
for (var i = 1; i <= diff; i++) {
left();
}
}
else {
//same element is clicked....do nothing
//alert(clickedIndex);
document.getElementById("coverflow").style.display="none";
document.getElementById("fig"+clickedIndex+"_content").style.display="block";
}
}
}
/* Functions - left() & right() for actually moving the images when user interacts*/
/* Move an image from L -> R i.e you are swiping from L->R across the screen */
function left() {
if (current > min) {
current--;
for (var i = 1; i <= max; i++) {
currPos = document.getElementById("fig" + i).getAttribute("cp");
currAngle = document.getElementById("fig" + i).getAttribute("a");
if (currPos == "-150" || currPos == "0") {
newPos = parseInt(currPos) + (gap * 2) * (1);
if (currPos == "0") {
newAngle = -30;
}
else if (currPos = "-150") {
newAngle = 0;
}
else {
}
}
else {
newPos = parseInt(currPos) + (gap) * (1);
newAngle = parseInt(currAngle);
}
if (i == current) {
document.getElementById("fig" + i).style.webkitTransform = "translateX(" + newPos + "px) rotateY(" + newAngle + "deg) translateZ(200px)";
}
else {
document.getElementById("fig" + i).style.webkitTransform = "translateX(" + newPos + "px) rotateY(" + newAngle + "deg)";
}
document.getElementById("fig" + i).setAttribute("cp", newPos);
document.getElementById("fig" + i).setAttribute("a", newAngle);
}
}
}
/* Move an image from R -> L i.e you are swiping from R->L across the screen */
function right() {
if (current < max) {
current++;
for (var i = 1; i <= max; i++) {
currPos = document.getElementById("fig" + i).getAttribute("cp");
currAngle = document.getElementById("fig" + i).getAttribute("a");
if (currPos == "150" || currPos == "0") {
newPos = parseInt(currPos) + (gap * 2) * (-1);
if (currPos == "0") {
newAngle = 30;
}
else if (currPos = "150") {
newAngle = 0;
}
else {
}
}
else {
newPos = parseInt(currPos) + (gap) * (-1);
newAngle = parseInt(currAngle);
}
if (i == current) {
document.getElementById("fig" + i).style.webkitTransform = "translateX(" + newPos + "px) rotateY(" + newAngle + "deg) translateZ(200px)";
}
else {
document.getElementById("fig" + i).style.webkitTransform = "translateX(" + newPos + "px) rotateY(" + newAngle + "deg)";
}
document.getElementById("fig" + i).setAttribute("cp", newPos);
document.getElementById("fig" + i).setAttribute("a", newAngle);
}
}
}
and the other Js is referenced in a script file named as: coverflow-type.js
var min = 1; //minimum number of image
var max = 5; //maximum number of images
var current = 3; //image number that is at the center of the coverflow
var currPos = 0; //custom attribute that stores current TranslateX position of each image
var newPos = 0; //custom attribute that stores new TranslateX position of each image, i.e after movement
var currAngle = 0; //custom attribute that stores current RotationY angle of each image
var newAngle = 0; //custom attribute that stores new RotationY angle of each image
var gap = 75;
var clickedIndex = 0; //index of the image tapped
var isMouseDown = false; //has the user interacted
var swipeStartX = 0;
var swipeDistanceX = 0;
var diff = 0;
var imageTapStartX = 0;
var imageTapEndX = 0;
var imageTapDistanceX= 0;
var coverFlowContainerElement = null;
var thresholdDistanceSingleSlide = 0; //this measures the distance
window.addEventListener("load",function(){
/* Hide the browser address bar. This will give a native feel to the app */
setTimeout(function() { window.scrollTo(0, 1); }, 20);
/* Get the pointer to the coverflow holder */
coverFlowContainerElement = document.getElementById("coverflow");
moveImagesFromRight(); //help comments are there in the function definition
addEventsToImageHolders(); //help comments are there in the function definition
addEventToCoverflowHolder(); //help comments are there in the function definition
thresholdDistanceSingleSlide = parseInt(300 / max);
disablePageScroll(); //help comments are there in the function definition
},false);
/*
Give the initial thrust to the slides from the right. I have just given it an effect of the images being
thrown into the center from the right.
*/
function moveImagesFromRight()
{
setTimeout(function() {
document.getElementById("fig1").style.webkitTransform = "translateX(-225px) rotateY(30deg)";
document.getElementById("fig2").style.webkitTransform = "translateX(-150px) rotateY(30deg)";
document.getElementById("fig3").style.webkitTransform = "translateX(0px) rotateY(0deg) translateZ(200px)";
document.getElementById("fig4").style.webkitTransform = "translateX(150px) rotateY(-30deg)";
document.getElementById("fig5").style.webkitTransform = "translateX(225px) rotateY(-30deg)";
}, 150);
}
/* Register touch event listener to the image holders i.e the <div> holding each images */
function addEventsToImageHolders()
{
var imageHolders = coverFlowContainerElement.getElementsByTagName("div");
for(var i=0;i<imageHolders.length;i++)
{
//console.log(imageHolders[i]);
imageHolders[i].addEventListener("touchstart",handleImageTapStart,false);
imageHolders[i].addEventListener("touchend",handleImageTapEnd,false);
}
}
/*
Add touch events to the <div id='coverflow' /> container. So the container registers the finger movements
and acts accordingly
*/
function addEventToCoverflowHolder()
{
coverFlowContainerElement.addEventListener("touchstart", handleFingerSwipeStart, false);
coverFlowContainerElement.addEventListener("touchmove", handleFingerSwipeMove, false);
coverFlowContainerElement.addEventListener("touchend", handleFingerSwipeEnd, false);
}
/* The default behavior of the browser is to scroll when you swipe. This line is to prevent scrolling */
function disablePageScroll() {
document.ontouchmove = function(event) {
event.preventDefault();
}
}
/* Events for the <div id='coverflow'></div> holder */
function handleFingerSwipeStart(event) {
isMouseDown = true;
swipeStartX = event.changedTouches[0].pageX;
event.preventDefault();
}
function handleFingerSwipeMove(event) {
if (isMouseDown) {
swipeDistanceX = parseInt(event.changedTouches[0].pageX - swipeStartX);//
var netDistance = Math.abs(swipeDistanceX);
//console.log("Move: " + swipeDistanceX + " Net distance: " + netDistance); //changedTouches[0].
if (netDistance >= thresholdDistanceSingleSlide) {
//console.log(thresholdDistanceSingleSlide + " covered");
if (swipeDistanceX < 0) {
right();
swipeStartX = event.changedTouches[0].pageX;
}
else {
left();
swipeStartX = event.changedTouches[0].pageX;
}
}
}
}
function handleFingerSwipeEnd(event) {
if (isMouseDown) {
isMouseDown = false;
swipeStartX = 0;
}
}
/*
Events for the <div id="fig"></div> elements where fig starts from 1 to 7. The images are
inside these element
*/
function handleImageTapStart(event) {
imageTapStartX = event.changedTouches[0].pageX;
}
function handleImageTapEnd(event) {
imageTapEndX = event.changedTouches[0].pageX;
imageTapDistanceX = imageTapEndX - imageTapStartX;
var targetObj = event.currentTarget;
if (imageTapDistanceX == 0) {
clickedIndex = parseInt(targetObj.id.slice(3, 4));
if (clickedIndex > current) {
//move right to the clicked index
diff = clickedIndex - current;
for (var i = 1; i <= diff; i++) {
right();
}
}
else if (clickedIndex < current) {
//move left to the clicked index
diff = (current - clickedIndex);
for (var i = 1; i <= diff; i++) {
left();
}
}
else {
//same element is clicked....do nothing
// alert(clickedIndex);
console.log(targetObj);
var thumbfile=targetObj.getAttribute("rel");
document.getElementById("coverflow").style.display="none";
document.getElementById("content").style.display="block";
var thumbList=show(thumbfile);
document.getElementById("Tlist").innerHTML=thumbList;
window.mySwipe = new Swipe(document.getElementById('slider'),{
callback: function(e, pos) {
var i = bullets.length;
while (i--) {
bullets[i].className = '';
}
bullets[pos].className = 'on';
}
}),
bullets = document.getElementById('position').getElementsByTagName('span');
}
}
}
/* Functions - left() & right() for actually moving the images when user interacts*/
/* Move an image from L -> R i.e you are swiping from L->R across the screen */
function left() {
if (current > min) {
current--;
for (var i = 1; i <= max; i++) {
currPos = document.getElementById("fig" + i).getAttribute("cp");
currAngle = document.getElementById("fig" + i).getAttribute("a");
if (currPos == "-150" || currPos == "0") {
newPos = parseInt(currPos) + (gap * 2) * (1);
if (currPos == "0") {
newAngle = -30;
}
else if (currPos = "-150") {
newAngle = 0;
}
else {
}
}
else {
newPos = parseInt(currPos) + (gap) * (1);
newAngle = parseInt(currAngle);
}
if (i == current) {
document.getElementById("fig" + i).style.webkitTransform = "translateX(" + newPos + "px) rotateY(" + newAngle + "deg) translateZ(200px)";
}
else {
document.getElementById("fig" + i).style.webkitTransform = "translateX(" + newPos + "px) rotateY(" + newAngle + "deg)";
}
document.getElementById("fig" + i).setAttribute("cp", newPos);
document.getElementById("fig" + i).setAttribute("a", newAngle);
}
}
}
/* Move an image from R -> L i.e you are swiping from R->L across the screen */
function right() {
if (current < max) {
current++;
for (var i = 1; i <= max; i++) {
currPos = document.getElementById("fig" + i).getAttribute("cp");
currAngle = document.getElementById("fig" + i).getAttribute("a");
if (currPos == "150" || currPos == "0") {
newPos = parseInt(currPos) + (gap * 2) * (-1);
if (currPos == "0") {
newAngle = 30;
}
else if (currPos = "150") {
newAngle = 0;
}
else {
}
}
else {
newPos = parseInt(currPos) + (gap) * (-1);
newAngle = parseInt(currAngle);
}
if (i == current) {
document.getElementById("fig" + i).style.webkitTransform = "translateX(" + newPos + "px) rotateY(" + newAngle + "deg) translateZ(200px)";
}
else {
document.getElementById("fig" + i).style.webkitTransform = "translateX(" + newPos + "px) rotateY(" + newAngle + "deg)";
}
document.getElementById("fig" + i).setAttribute("cp", newPos);
document.getElementById("fig" + i).setAttribute("a", newAngle);
}
}
}
// show thumbnails functions
//function show(dname){
// if(window.XMLHttpRequest){
// xhttp=new XMLHttpRequest();
// }
// else{
// xhttp=new ActiveXObject(Microsoft.XMLHTTP);
// }
// xhttp.open("GET",dname,false);
// xhttp.send();
// var xmlDoc=xhttp.responseXML;
// var thumblist=xmlDoc.getElementsByTagName("asset");
// //str="";
// str="<li>";
// var image= new Array();
// for(i=0, tc=1; i<thumblist.length;i++){
// var x=thumblist[i].childNodes;
// for(j=0,index=0; j<x.length;j++){
// if(x[j].nodeType==1){
// image[index]=(x[j].firstChild.nodeValue);
// index++;
// }
// x[j]=x[j].nextSibling;
// }
// str+='<div><img src="'+image[0]+'"><span>'+image[1]+'</span></div>';
// // tc<thumblist.length check for the last node
// if(tc%6==0&& tc<thumblist.length){
// str+="</li><li>";
// }
// tc++;
// // str+='<div class="thumbwrapper"><img src="'+image[0]+'">'+image[1]+'</div>';
// //str+='<li><img src="'+image[0]+'"><span>'+image[1]+'</span></li>';
// }
// str+="</li>";
// //alert(str);
// console.log(str);
// return str;
// }
function show(dname){
if(window.XMLHttpRequest){
xhttp=new XMLHttpRequest();
}
else{
xhttp=new ActiveXObject(Microsoft.XMLHTTP);
}
xhttp.open("GET",dname,false);
xhttp.send();
var xmlDoc=xhttp.responseXML;
var thumblist=xmlDoc.getElementsByTagName("asset");
//str="";
str="<li>";
var image= new Array();
for(i=0, tc=1; i<thumblist.length;i++){
// getting the attribute node of every assets
var thumb=thumblist[i].attributes;
str+='<div><img src="'+thumb.getNamedItem("thumbnail").nodeValue+'"><span>'+thumb.getNamedItem("title").nodeValue+'</span></div>';
// (tc<thumblist.length) check for the last node
if(tc%6==0&& tc<thumblist.length){
str+="</li><li>";
}
tc++;
}
str+="</li>";
//alert(str);
console.log(str);
return str;
}
Here's my HTML:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0,maximum-scale=1.0, user-scalable=no">
<title>GRAAVAA HTML5</title>
<link href="css/bgLandscape.css" rel="stylesheet" type="text/css">
<link href="css/bgLandscape.css" media="screen and (device-width:768px) and (orientation:landscape) or (-webkit-min-device-pixel-ratio: 2)" rel="stylesheet" type="text/css">
<link rel="stylesheet" type="text/css" href="css/login.css" />
<link href="css/coverflow.css" type="text/css" rel="stylesheet"/>
<script type="text/javascript" src="js/modernizr.custom.86080.js"></script>
<script src="js/jquery-1.8.2.min.js"></script>
</head>
<body>
<div class="bg">
<ul class="cb-slideshow">
<li><span></span></li>
<li><span></span></li>
<li><span></span></li>
<li><span></span></li>
<li><span></span></li>
<li><span></span></li>
<li><span></span></li>
</ul>
<div id="formContainer" class="formContainer">
<form id="login" method="post" action="index.html" class="login">
<span id="msg" class="error"></span>
<!-- <input type="email" name="email" id="email" value="Email Address" class="stored" required="required" placeholder="admin#mail.com"/>-->
<input type="email" name="email" id="email" placeholder="Email Address" class="email" style="top:176px;" />
<input type="text" name="name" id="name" placeholder="Full Name" class="stored"/>
<!--<input type="reset" name="reset" value="Skip" />-->
<input type="button" name="skip" id="skip" value="Skip" class="skip" />
<input type="submit" name="submit" value="Save" class="submit" />
</form>
</div>
<!-- Collection By Type -->
<div id="wrapperType" class="collectionTypeWrapper">
<div class="container">
<div id="coverflow">
<div id="fig1" cp="-225" a="30" rel="xml/granite.xml"><img src="collectionType/granite.jpg" /></div>
<div id="fig2" cp="-150" a="30" rel="xml/marble.xml"><img src="collectionType/marble.jpg" /></div>
<div id="fig3" cp="0" a="0" rel="xml/onyx.xml"><img src="collectionType/onyx.jpg" /></div>
<div id="fig4" cp="150" a="-30" rel="xml/travertine.xml"><img src="collectionType/travertine.jpg" /></div>
<div id="fig5" cp="225" a="-30" rel="xml/limitededition.xml"><img src="collectionType/limited.jpg" /></div>
</div>
</div>
</div>
<!-- Collection By Color -->
<div id="wrapperColor" class="collectionColorWrapper">
<div class="container">
<div id="coverflow">
<div id="fig1" cp="-150" a="30" rel="xml/natural.xml"><img src="collectionColor/neutral.jpg" /></div>
<div id="fig2" cp="0" a="0" rel="xml/dark.xml"><img src="collectionColor/dark.jpg" /></div>
<div id="fig3" cp="150" a="-30" rel="xml/vivid.xml"><img src="collectionColor/vivid.jpg" /></div>
</div>
</div>
</div>
<div id="popupicon">
<img id="collectionColor" src="images/1.png" style="margin-left:15px" />
<img id="collectionType" src="images/2.png" style="margin:0px 0px 5px 35px" />
</div>
<div id="bottomImgWrapper" class="bottomImgWrapper"></div>
<div id="bottomImg" class="bottomImg" >
<img src="images/collection.png" class="graavaaImag" id="collection" />
<img src="images/application.png" class="graavaaImag" />
<img src="images/showrooms.png" class="graavaaImag"/>
<img src="images/menuLogo.png" class="graavaaIcon" />
</div>
</div>
<script type="text/javascript">
$("img#collection").click(function(e){
e.preventDefault();
$("#popupicon").fadeToggle("slow");
});
$('#skip').click(function(){
//localStorage.clear();
$("#formContainer").css("display","none");
$("#bottomImgWrapper").css("display","block");
$("#bottomImg").css("display","block");
// setting the skip flag
sessionStorage.setItem('flag','true');
});
$('.login').submit(function() {
var email=$(this).children("#email").val();
var name=$(this).children("#name").val();
var result=validateEmail($(this).children("#email").val());
if(result==false){
//$(this).focus();
$(".error").html('Invalid Email Address');
$(".email").focus();
return false;
}
if(result==true){
$(".error").html('');
localStorage[$("#email").attr('name')] = email;
localStorage[$("#name").attr('name')] = name;
alert('Thank You for saving information');
$("#formContainer").css("display","none");
$(".bottomImgWrapper").css("display","block");
$(".bottomImg").css("display","block");
// Dont submit the form in any condition : as it refresh the page
return false;
//return true;
}
return false;
});
$('#collectionType').click(function(){
$(".collectionTypeWrapper").css("display","block");
$(".collectionColorWrapper").css("display","none");
$("#collectionColor").hide(".collectionTypeWrapper");
$("#collectionColor").show(".collectionTypeWrapper");
//$(".collectionTypeWrapper").fadeIn("slow");
//$(".collectionColorWrapper").fadeOut("slow");
$("#popupicon").fadeToggle("slow");
});
$('#collectionColor').click(function(){
$(".collectionColorWrapper").css("display","block");
$(".collectionTypeWrapper").css("display","none");
//$(".collectionTypeWrapper").fadeOut("slow");
//$(".collectionColorWrapper").fadeIn("slow");
$("#popupicon").fadeToggle("slow");
});
function validateEmail(txtEmail){
var filter = /^((\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*?)\s*;?\s*)+/;
if(filter.test(txtEmail)){
return true;
}
else{
return false;
}
}
$(document).ready(function(e) {
function init() {
//localStorage.clear();
// show the login form if localstorage not persent
if(!localStorage["email"]){
$("#formContainer").css({"display":"block"});
// hide the bottom images initially
$("#bottomImgWrapper").css("display","none");
$("#bottomImg").css("display","none");
}
// storing the value into application session
if(sessionStorage.flag=="true"){
$("#formContainer").css({"display":"none"});
$("#bottomImgWrapper").css("display","block");
$("#bottomImg").css("display","block");
}
if(localStorage["email"]){
$("#formContainer").css("display","none");
alert('You are already saved as : '+ localStorage["email"]);
}
}
init();
});
</script>
<script type="text/javascript" src="js/coverflow-color.js"></script>
<script type="text/javascript" src="js/coverflow-type.js"></script>
</body>
</html>
It is not going to work because of global variables. The second one overwrites the first one. You also make multiple elements with the same ids. Ids are SINGULAR, you can not have more than one element with the same id.

Check if all percentages in the array were shown

I'm using this Code to show the current progress in my progressbar:
var rotatingTextElement;
var rotatingText = new Array();
var ctr = 0;
function initRotateText() {
rotatingTextElement = document.getElementById("percent");
rotatingText[0] = rotatingTextElement.innerHTML;
rotatingText[1] = "5%";
rotatingText[2] = "10%";
rotatingText[3] = "15%";
rotatingText[4] = "20%";
rotatingText[5] = "25%";
rotatingText[6] = "30%";
rotatingText[7] = "35%";
rotatingText[8] = "40%";
rotatingText[9] = "45%";
rotatingText[10] = "50%";
rotatingText[11] = "55%";
rotatingText[12] = "60%";
rotatingText[13] = "65%";
rotatingText[14] = "70%";
rotatingText[15] = "75%";
rotatingText[16] = "80%";
rotatingText[17] = "85%";
rotatingText[18] = "90%";
rotatingText[19] = "95%";
rotatingText[20] = "100%";
setInterval(rotateText, 500);
}
function rotateText() {
ctr++;
if(ctr >= rotatingText.length) {
ctr = 0;
}
rotatingTextElement.innerHTML = rotatingText[ctr];
}
window.onload = initRotateText;
It basicly writs a new percentage in span#percent every 500 miliseconds.
The problem is that after the progressbar has reached 100% it starts again with 0%, 5% and so on.
How can I check if the percentages in the array rotatingText till [20] were all shown and then stop the rotation?
Do this instead:
var rotatingTextElement = document.getElementById("percent");
var ctr = 0;
function rotateText() {
rotatingTextElement.innerHTML = ctr + "%";
ctr += 5;
if (ctr <= 100) {
window.setTimeout(rotateText, 500);
}
}
rotateText();
There are a few ways you can tidy this up. To answer your question, start by assigning the interval to a variable:
var rotator = null;
...
rotator = setInterval(rotateText, 500);
...
function rotateText() {
ctr++;
if(ctr >= rotatingText.length -1) {
clearInterval(rotator);
}
rotatingTextElement.innerHTML = rotatingText[ctr];
}
...
Then instead of resetting the iterator to 0 when it goes out of bounds, clear the interval so it stops changing the value. You'll need to add the -1 so that it stops on rotatingText[length-1] (the last element)

Categories

Resources