Display javaScript variable value on HTML page? - javascript

I write a game java script code i need to display the score variable points in HTML. I try it but it always print 0 and not increment the score. The Score variable is increment by 1 but on HTML page it keep showing 0.Where Should i change in tag to properly display it or should i need to change it java script score function ?
My Java Script code :
var notes = [];
var gameStarted = false;
var Score = 0;
// ==== CLASS FOR ARROWS ==== //
// 1. Direction of arrows
// 2. jQuery img that links to direction bottom
// 3. Destroy when it arrow gets to the
// 4. Explode when arrow gets to the bottom
// Class Arrow
function Arrow(direction) {
// CSS spacings for the arrows //
var xPos = null;
switch(direction) {
case "left" : xPos = "350px";
break;
case "up" : xPos = "420px";
break;
case "down" : xPos = "490px";
break;
case "right" : xPos = "560px";
break;
}
this.direction = direction;
this.image = $("<img src='./arrows/" + direction + ".gif'/>");
this.image.css({
position: "absolute",
top: "0px",
left: xPos
});
$('.stage').append(this.image);
}// ends CLASS Arrow
// To enable animating the arrows
Arrow.prototype.step = function() {
// Controls the speed of the arrows
this.image.css("top", "+=4px");
};
// Deletes arrows when they get to bottom of page
Arrow.prototype.destroy = function() {
// removes the image of the DOM
this.image.remove();
// Removes the note/arrow from memory/array
notes.splice(0,1);
};
// Explodes arrow when hit
Arrow.prototype.explode = function() {
this.image.remove();
};
// For random arrows
var randNum = 0;
// Frame increasing
var frame = 0;
// Determines the speed of notes
var arrowSpawnRate = 40;
// Random generator for arrows
function randomGen() {
// Randomizes between 1 and 4
randNum = Math.floor(Math.random() * 4) + 1;
if (randNum === 1) {
notes.push(new Arrow("left"));
}
if (randNum === 2) {
notes.push(new Arrow("right"));
}
if (randNum === 3) {
notes.push(new Arrow("up"));
}
if (randNum === 4) {
notes.push(new Arrow("down"));
}
}// ends randomGen()
// Render function //
function render() {
if (frame++ % arrowSpawnRate === 0) {
randomGen();
}
// Animate arrows showering down //
for (var i = notes.length - 1; i >= 0; i--) {
notes[i].step();
// Check for cleanup
if (notes[i].image.position().top > 615) {
notes[i].destroy();
}
}
}// ends render()
// jQuery to animate arrows //
$(document).ready(function () {
// shim layer with setTimeout fallback
window.requestAnimFrame = (function() {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 40 / 75);
};
})();
/* place the rAF *before* the render()
to assure as close to 60fps with the
setTimeout fallback. */
// Infinte loop for game play
(function animloop() {
if (gameStarted) {
requestAnimFrame(animloop);
render();
} else {
window.setTimeout(animloop, 1000); // check the state per second
}
})();// ends (function animloop() )
});// ends $(doc).ready
// Listening for when the key is pressed
$(document).keydown( function(event) {
for (var i = 0; i < notes.length; i++) {
console.log(notes[i].image.position().top);
if (event.keyCode == 37 && notes[i].direction == "left") {
if (notes[i].image.position().top > 490 && notes[i].image.position().top < 730) {
console.log("LEFT! "+notes[i].explode());
Score++;
}
}
if (event.keyCode == 38 && notes[i].direction == "up") {
if (notes[i].image.position().top > 490 && notes[i].image.position().top < 730) {
console.log("UP! "+notes[i].explode());
Score++;
}
}
if (event.keyCode == 40 && notes[i].direction == "down") {
if (notes[i].image.position().top > 490 && notes[i].image.position().top < 730) {
console.log("DOWN! "+notes[i].explode());
Score++;
}
}
if (event.keyCode == 39 && notes[i].direction == "right") {
if (notes[i].image.position().top > 490 && notes[i].image.position().top < 730) {
console.log("RIGHT! "+notes[i].explode());
Score++;
}
}
}// ends loop
});// ends $(doc).keyup
function score() {
document.getElementById("Points").innerHTML = Score;
}
HTML code:
<html>
<head>
<link rel="icon" href="./arrows/clubbackground.jpg" type="image/gif" sizes="16x16">
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="jsRev.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<title>DDR-Project 1</title>
</head>
<body>
<div id="BackgroundScene">
<div id="DanceScoreboard">
<div id="GameStopped"><button id="StartBtn" class="btnStyle" onclick="gameStarted=true;">Begin Game</button>
<br><br><br><div class="Status">Click Begin Game to start</div>
</div>
<div id="GameRunning"><button id="StopBtn" class="btnStyle" onclick="gameStarted=false;">Stop Game</button>
<div id="Status" class="Status"></div>
</div>
<div id="dancePoints" class="Points">Points Earned: <div class="OutputText" id="CorrectCount">0</div>
</div>
</div>
<div class="stage"></div> <!-- ENDS .STAGE -->
<div id="controls">
<img id="left" src="./arrows/staticLeft.png">
<img id="up" src="./arrows/staticUp.png">
<img id="down" src="./arrows/staticDown.png">
<img id="right" src="./arrows/staticRight.png">
</div> <!-- ENDS #CONTROLS -->
</body>
</html>

Call the score function whenever, the Score variable gets updated. In your html there is not element with id Points, however class is present. Instead of document.getElementById("Points").innerHTML = Score; use document.querySelector(".Points").textContent = Score;. No need to use innerHTML, as Score is a number and not an html content.
var notes = [];
var gameStarted = false;
var Score = 0;
// ==== CLASS FOR ARROWS ==== //
// 1. Direction of arrows
// 2. jQuery img that links to direction bottom
// 3. Destroy when it arrow gets to the
// 4. Explode when arrow gets to the bottom
// Class Arrow
function Arrow(direction) {
// CSS spacings for the arrows //
var xPos = null;
switch (direction) {
case "left":
xPos = "350px";
break;
case "up":
xPos = "420px";
break;
case "down":
xPos = "490px";
break;
case "right":
xPos = "560px";
break;
}
this.direction = direction;
this.image = $("<img src='./arrows/" + direction + ".gif'/>");
this.image.css({
position: "absolute",
top: "0px",
left: xPos
});
$('.stage').append(this.image);
} // ends CLASS Arrow
// To enable animating the arrows
Arrow.prototype.step = function() {
// Controls the speed of the arrows
this.image.css("top", "+=4px");
};
// Deletes arrows when they get to bottom of page
Arrow.prototype.destroy = function() {
// removes the image of the DOM
this.image.remove();
// Removes the note/arrow from memory/array
notes.splice(0, 1);
};
// Explodes arrow when hit
Arrow.prototype.explode = function() {
this.image.remove();
};
// For random arrows
var randNum = 0;
// Frame increasing
var frame = 0;
// Determines the speed of notes
var arrowSpawnRate = 40;
// Random generator for arrows
function randomGen() {
// Randomizes between 1 and 4
randNum = Math.floor(Math.random() * 4) + 1;
if (randNum === 1) {
notes.push(new Arrow("left"));
}
if (randNum === 2) {
notes.push(new Arrow("right"));
}
if (randNum === 3) {
notes.push(new Arrow("up"));
}
if (randNum === 4) {
notes.push(new Arrow("down"));
}
} // ends randomGen()
// Render function //
function render() {
if (frame++ % arrowSpawnRate === 0) {
randomGen();
}
// Animate arrows showering down //
for (var i = notes.length - 1; i >= 0; i--) {
notes[i].step();
// Check for cleanup
if (notes[i].image.position().top > 615) {
notes[i].destroy();
}
}
} // ends render()
// jQuery to animate arrows //
$(document).ready(function() {
// shim layer with setTimeout fallback
window.requestAnimFrame = (function() {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 40 / 75);
};
})();
/* place the rAF *before* the render()
to assure as close to 60fps with the
setTimeout fallback. */
// Infinte loop for game play
(function animloop() {
if (gameStarted) {
requestAnimFrame(animloop);
render();
} else {
window.setTimeout(animloop, 1000); // check the state per second
}
})(); // ends (function animloop() )
}); // ends $(doc).ready
// Listening for when the key is pressed
$(document).keydown(function(event) {
for (var i = 0; i < notes.length; i++) {
if (event.keyCode == 37 && notes[i].direction == "left") {
if (notes[i].image.position().top > 490 && notes[i].image.position().top < 730) {
console.log("LEFT! " + notes[i].explode());
Score++;
score();
}
}
if (event.keyCode == 38 && notes[i].direction == "up") {
if (notes[i].image.position().top > 490 && notes[i].image.position().top < 730) {
console.log("UP! " + notes[i].explode());
Score++;
score();
}
}
if (event.keyCode == 40 && notes[i].direction == "down") {
if (notes[i].image.position().top > 490 && notes[i].image.position().top < 730) {
console.log("DOWN! " + notes[i].explode());
Score++;
score();
}
}
if (event.keyCode == 39 && notes[i].direction == "right") {
if (notes[i].image.position().top > 490 && notes[i].image.position().top < 730) {
console.log("RIGHT! " + notes[i].explode());
Score++;
score();
}
}
} // ends loop
}); // ends $(doc).keyup
function score() {
document.querySelector(".Points").textContent = Score;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="BackgroundScene">
<div id="DanceScoreboard">
<div id="GameStopped"><button id="StartBtn" class="btnStyle" onclick="gameStarted=true;">Begin Game</button>
<br><br><br>
<div class="Status">Click Begin Game to start</div>
</div>
<div id="GameRunning"><button id="StopBtn" class="btnStyle" onclick="gameStarted=false;">Stop Game</button>
<div id="Status" class="Status"></div>
</div>
<div id="dancePoints" class="Points">Points Earned:
<div class="OutputText" id="CorrectCount">0</div>
</div>
</div>
<div class="stage"></div>
<!-- ENDS .STAGE -->
<div id="controls">
<img id="left" src="./arrows/staticLeft.png">
<img id="up" src="./arrows/staticUp.png">
<img id="down" src="./arrows/staticDown.png">
<img id="right" src="./arrows/staticRight.png">
</div>
<!-- ENDS #CONTROLS -->
Note - Use class names or id names in lower case whenever possible, as minor mistake in casing would make it difficult to identify the error.

Related

Pure JavaScript Slideshow Play/Pause with Spacebar

I'm trying to make a JavaScript slideshow (here's the fiddle) with automatically-playing audio for each slide with the functionality to allow right arrow (for next slide), left arrow (for previous slide), or space bar to play from the current slide to the last slide, with space bar also being used to pause the slideshow (and then again to resume, etc.).
The only problem I am experiencing is with getting the space bar to pause the slideshow. For debugging, I'm logging to the console when it is suppose to pause, and it seems to be executing this functionality the number of times as the slide number, albeit without actually pausing the slideshow--e.g. if I push space bar when on slide 2, it executes twice, but if I push space bar yet again when it reaches slide 4, it executes 6 times (2+4), etc.
I have tried the following code most recently to no avail:
(function loop(){
var breakout;
window.addEventListener('keydown', function(secondkey) {if (secondkey.keyCode == 32){breakout = "1"; console.log("paused on slide #" + slidenumber + "!");}})
if (slidenumber >= slidelength || breakout == "1") return;
setTimeout(function(){
if (breakout == "1") return;
console.log("slide #: " + slidenumber);
showDivs(slidenumber += 1);
loop();
}, 1000);
})();
I've also tried this failing code:
(function loop() {
var breakout;
window.addEventListener('keydown', function(secondkey) {if (secondkey.keyCode == 32){breakout = "1"; console.log("paused on slide #" + slidenumber + "!");}})
setTimeout(function() {
if (slidenumber >= slidelength || breakout == "1") {console.log("breakout on slide #" + slidenumber + "!"); return;}
else {
console.log("slide ##: " + slidenumber);
showDivs(slidenumber += 1);
loop();
}
},1000);
})();
...and this failing code:
for (a = slidenumber; a < slidelength; a++) {
var breakout;
window.addEventListener('keydown', function(secondkey) {if (secondkey.keyCode == 32){breakout = "1"; console.log("paused!");}})
if (breakout == "1"){break;}
(function(ind) {
setTimeout(function(){
showDivs(slidenumber += 1);
}, 2 * 1000 * ind); // Change slide every 2 seconds
})(a);
}
And even this failing code:
var func = function(slidenumber){
return function(){
if (slidenumber >= slidelength) return;
console.log("turn no. " + slidenumber);
showDivs(slidenumber += 1);
var breakout;
window.addEventListener('keydown', function(secondkey) {if (secondkey.keyCode == 32){breakout = "1"; console.log("paused!");}})
if(breakout == "1") {
console.log('slideshow paused');
} else {
setTimeout(func(++slidenumber), 2000);
}
}
}
setTimeout(func(0), 2000);
What can I do to get this to work? My entire code is:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Slideshow</title>
</head>
<body style="text-align: center;">
<div class="slide-content">
<img style="height:80vh;" onclick="play(1)" src="https://images.unsplash.com/photo-1541963463532-d68292c34b19?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxleHBsb3JlLWZlZWR8Mnx8fGVufDB8fHx8&auto=format&fit=crop&w=700&q=60">
<audio id="audio-1" src="https://soundbible.com/grab.php?id=2218&type=mp3"></audio>
</div>
<div class="slide-content">
<img style="height:80vh;" onclick="play(2)" src="https://images.unsplash.com/photo-1546521343-4eb2c01aa44b?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxleHBsb3JlLWZlZWR8M3x8fGVufDB8fHx8&auto=format&fit=crop&w=700&q=60">
<audio id="audio-2" src="http://soundbible.com/grab.php?id=2212&type=mp3"></audio>
</div>
<div class="slide-content">
<img style="height:80vh;" onclick="play(3)" src="https://images.unsplash.com/photo-1543002588-bfa74002ed7e?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxleHBsb3JlLWZlZWR8MXx8fGVufDB8fHx8&auto=format&fit=crop&w=700&q=60">
<audio id="audio-3" src="http://soundbible.com/grab.php?id=2210&type=mp3"></audio>
</div>
<div class="slide-content">
<img style="height:80vh;" onclick="play(4)" src="https://images.unsplash.com/photo-1507842217343-583bb7270b66?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxleHBsb3JlLWZlZWR8Nnx8fGVufDB8fHx8&auto=format&fit=crop&w=700&q=60">
<audio id="audio-4" src="http://soundbible.com/grab.php?id=2204&type=mp3"></audio>
</div>
<div class="slide-content">
<img style="height:80vh;" onclick="play(5)" src="https://images.unsplash.com/photo-1532012197267-da84d127e765?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxleHBsb3JlLWZlZWR8NHx8fGVufDB8fHx8&auto=format&fit=crop&w=700&q=60">
<audio id="audio-5" src="http://soundbible.com/grab.php?id=2184&type=mp3"></audio>
</div>
<div onclick="plusDivs(-1)">Previous</div>
<div onclick="plusDivs(1)">Next</div>
<script>
var slidelength = document.getElementsByClassName("slide-content").length;
function play(nr) {
var audio = document.getElementById("audio-"+nr); audio.play();
}
var slidenumber = 1;
showDivs(slidenumber);
function plusDivs(n) {
showDivs(slidenumber += n);
}
function showDivs(n) {
var i;
var slide = document.getElementsByClassName("slide-content");
if (n > slidelength) {slidenumber = n-1} // Do not loop
if (n < 1) {slidenumber = n+1} // If left is pushed on first slide, stay on first slide
for (i = 0; i < slidelength; i++) {
slide[i].style.display = "none";
}
slide[slidenumber-1].style.display = "block";
console.log("# of slides: " + slidelength);
console.log("slide #: " + slidenumber);
play(slidenumber);
}
window.addEventListener('keydown', function(pronounce) {
if (pronounce.keyCode == 39) {showDivs(slidenumber += 1);} // Right Arrow
if (pronounce.keyCode == 37) {showDivs(slidenumber -= 1);} // Left Arrow
// Space bar, when pushed, should loop through automatically until last slide. if space bar is pushed again pause. if pushed yet again continue. etc.
if (pronounce.keyCode == 32) { // Space Bar
// Working, but not the pause
(function loop(){
var breakout;
window.addEventListener('keydown', function(secondkey) {if (secondkey.keyCode == 32){breakout = "1"; console.log("paused on slide #" + slidenumber + "!");}})
if (slidenumber >= slidelength || breakout == "1") return;
setTimeout(function(){
if (breakout == "1") return;
console.log("slide #: " + slidenumber);
showDivs(slidenumber += 1);
loop();
}, 1000);
})();
}
})
</script>
</body>
</html>

How can I restart this game using the button at the top?

I'm trying to make a simple snake game and so far most of it works, except restarting the game after the user has failed. I've added a button to the top and I'm hoping that a user can click the button to restart the game.
Here is the HTML
<head>
<meta charset="UTF-8">
<title>Snake</title>
</head>
<body>
<input type="button" id="restart" value="restart" style="font: normal 30px
monospace; color: white; background-color: blue;">Restart</input>
<h1 id="score" style="font: normal 50px monospace; color: white;">Score:
</h1>
</body>
the CSS
*{
padding: 0;
margin: 0;
}
body{
background-color: black;
}
td{
width: 20px;
height: 20px;
}
.blank{
background-color: blank;
}
.snake{
background-color: white;
border-radius: 50%;
}
.wall{
background-color: #cf1020;
}
.fruit{
background-color: gold;
border-radius: 50%;
}
The javaScript
//settings
var snakeX = 2;
var snakeY = 2;
var height = 28;
var width = 50;
var interval = 100;
var increment = 1;
//game variables
var length = 0;
var tailX = [snakeX];
var tailY = [snakeY];
var fX;
var fY;
var running = false;
var gameOver = false;
var direction = -1; // up = 0, down = -1, left = 1, right = 2
var int;
var score = 0;
//temporary direction (this fixes users pressing keys too quickly and
turning into themselves)
var tempdir = direction;
/**
* entry point of the game
*/
function run(){
init();
int = setInterval(gameLoop, interval);
}
function init(){
createMap();
createSnake();
createFruit();
}
/**
* Generates the map for the snake
*/
function createMap(){
document.write("<table>");
for( var y = 0; y < height; y++){
document.write("<tr>");
for( var x = 0; x < width; x++){
if(x == 0 || x == width -1 || y == 0 || y == height -1){
document.write("<td class='wall' id='"+ x + "-" + y +"'></td>");
}else{
document.write("<td class='blank' id='"+ x + "-" + y +"'>
</td>");
}
}
document.write("</tr>");
}
document.write("</table>");
}
function createSnake(){
set(snakeX, snakeY, "snake");
}
function get(x,y){
return document.getElementById(x+"-"+y);
}
function set(x,y,value){
if(x != null && y != null)
get(x,y).setAttribute("class", value);
}
function rand(min,max){
return Math.floor(Math.random() * (max - min) + min);
}
function getType(x,y){
return get(x,y).getAttribute("class");
}
function createFruit(){
var found = false;
while(!found && (length < (width-2)*(height-2)+1)){
var fruitX = rand(1,width-1);
var fruitY = rand(1,height-1);
if(getType(fruitX, fruitY) == "blank")
found = true;
}
set(fruitX, fruitY, "fruit");
fX = fruitX;
fY = fruitY;
}
/**
* NOTE: notice use of new variable tempdir
*/
window.addEventListener("keypress", function key(event){
//if key is W set direction up
var key = event.keyCode;
if(direction != -1 && (key == 119 || key == 87))
tempdir = 0;
//if key is S set direction down
else if(direction != 0 && (key == 115 || key == 83))
tempdir = -1;
//if key is A set direction left
else if(direction != 2 && (key == 97 || key == 65))
tempdir = 1;
//if key is D set direction right
else if(direction != 1 && (key == 100 || key == 68))
tempdir = 2;
if(!running)
running = true;
else if(key == 32)
running = false;
});
function gameLoop(){
if(running && !gameOver){
update();
}else if(gameOver){
clearInterval(int);
}
}
/**
* NOTE: notice use of new variable tempdir
*/
function update(){
direction = tempdir;
//prevents fruit from not showing up
set(fX, fY, "fruit");
//update the tail
updateTail();
//sets the last segment of the tail to blank before moving the snake
set(tailX[length], tailY[length], "blank");
//updates the position of the snake according to the direction
if(direction == 0)
snakeY--;
else if(direction == -1)
snakeY++;
else if(direction == 1)
snakeX--;
else if(direction == 2)
snakeX++;
//draws the head of the snake on the tail
set(snakeX, snakeY, "snake");
//checks for collisions with self
for(var i = tailX.length-1; i >=0; i--){
if(snakeX == tailX[i] && snakeY == tailY[i]){
gameOver = true;
break;
}
}
//checks for collision with wall
if(snakeX == 0 || snakeX == width-1 || snakeY == 0 || snakeY == height-1)
gameOver = true;
//checks for collisions with fruit
else if(snakeX == fX && snakeY == fY){
//adds 1 to the score
score+=1;
//creates new fruit, which automatically replaces the old one
createFruit();
//adds the set increment to the length of the snake making it longer
length+=increment;
}
//set
document.getElementById("score").innerHTML = "Score: "+ score;
}
function updateTail(){
for(var i = length; i > 0; i--){
tailX[i] = tailX[i-1];
tailY[i] = tailY[i-1];
}
tailX[0] = snakeX;
tailY[0] = snakeY;
}
run();
The Codepen
https://codepen.io/McComb/pen/EoYVRY
Not sure what requirements you have for this project, but i added jQuery to ease my work in it.
i added a new div in the body
<div id="canvas"></div>
i changed your createMap method with this :
/**
* Generates the map for the snake
*/
function createMap(){
var canvas;
canvas = '<table>';
for( var y = 0; y < height; y++){
canvas += "<tr>";
for( var x = 0; x < width; x++){
if(x == 0 || x == width -1 || y == 0 || y == height -1){
canvas += "<td class='wall' id='"+ x + "-" + y +"'></td>";
}else{
canvas += "<td class='blank' id='"+ x + "-" + y +"'></td>";
}
}
canvas += "</tr>" ;
}
$('#canvas').html(canvas);
}
and added a reset method
function reset()
{
//settings
snakeX = 2;
snakeY = 2;
height = 28;
width = 50;
interval = 100;
increment = 1;
//game variables
length = 0;
tailX = [snakeX];
tailY = [snakeY];
running = false;
gameOver = false;
direction = -1; // up = 0, down = -1, left = 1, right = 2
score = 0;
//temporary direction (this fixes users pressing keys too quickly and turning into themselves)
tempdir = direction;
clearInterval(int);
run();
// reset score
$('#score').text('Score: '+score);
}
here is the project with the changes :
https://codepen.io/anon/pen/vpBKyL

Link the movement of a div to the movement of another div

I'm making an alcohol simulator, so when I press a button, you see an alcohol bottle being drained, but at the same time I should see the stomach filling. I have a code already for 'drinking', but I want to fix that if the water of the bottle moves 2 steps, that the water of the stomach only moves one step. I'll put just the js here, if you want the html as well, let me know.
var top_max = 475,
top_min = 400,
left_max = 200;
function move_img(str) {
var step = 1; // change this to different step value
var el = document.getElementById('i1');
var el2 = document.getElementById('i2');
if (str == 'up' || str == 'down') {
var top = el.offsetTop;
var height = el.offsetHeight;
console.log(height);
if (str == 'up') {
top -= step;
height += step;
} else {
top += step;
height -=step;
}
if (top_max >= top && top >= 110) {
document.getElementById('i1').style.top = top + "px";
document.getElementById('i1').style.height = height;
} else {
clearInterval(myVar)
}
} else if (str == 'left' || str == 'right') {
var left = el.offsetLeft;
if (str == 'left') {
left += step;
} else {
left -= step;
}
if (top_left < left && left >= 0) {
document.getElementById('i1').style.left = top + "px";
} else {
clearInterval(myVar)
}
}
}
function auto(str) {
myVar = setInterval(function () {
move_img(str);
}, 90);
}
function nana() {}
var myVar;
function handler() {
clearInterval(myVar);
auto(this.id);
}
function auto(str) {
myVar = setInterval(function(){ move_img(str); }, 2) ;
}
function stop(){
setTimeout(function( ) { clearInterval( myVar ); }, 1);
}

Trying to debug a custom .sort in a JS array

A link to the Plunker.
I've been working on a button and list system in jQuery for awhile now. Recently I decided to make my code more reproducible. I want to make it so I just have to add classes or IDs, and I don't have to add any additional code. I'm very close to doing that for my entire site. So if you go to this site specifically you will see it in action.
If you click on any buttons, in any order, it will arrange chronologically.
The bugs come from closing them.
If you click at least three, close the middle one, then click a new button, the sort function falls apart and that closed middle one is now floating with the wrong class.
Below is my current jQuery. On my site, ignore the "All Years" button. I'll work on that after I figure out this bug.
//the variables needed for the floating buttons
var groupArray = $(".yearGroup");
var buttonArray = $(".buttonGroup");
var hideGroupArray = $(".hideGroup");
var closeBarArray = $(".closeBar");
var closeBar = $("#allCloseBar");
var allButtonArray = [];
sortElements = function(a,b)
{
if (a.text() < b.text())
{
return -1;
}
else if (a.text() > b.text())
{
return 1;
}
else
{
return 0;
}
}
$.each(buttonArray, function(i, item) {
$(this).click(function(){
console.log($(buttonArray[i]).text())
console.log($(closeBarArray[i]).text())
//for removing the tooltip when the button is clicked. Mostly for Firefox bug
$(".ui-tooltip-content").parents('div').remove();
$(hideGroupArray[i-1]).slideToggle(slideToggleDuration, function(){
htmlBody.animate({scrollTop: $(groupArray[i-1]).offset().top - 25}, {duration: timeDuration, easing: 'easeOutBack'});
$(buttonArray[i]).toggleClass("float", 1200);
if ($(groupArray[i-1]).height() > 0)
{
//This will stop any animations if the user scrolls.
htmlBody.bind("scroll mousedown DOMMouseScroll mousewheel keyup", function(e)
{
if ( e.which > 0 || e.type === "mousedown" || e.type === "mousewheel"){
htmlBody.stop().unbind('scroll mousedown DOMMouseScroll mousewheel keyup');
}
});
closeBar.addClass("floatCloseBar");
$(closeBarArray[i]).hide();
allButtonArray.splice(0, 0, $(buttonArray[i]));
var timer;
var delay = 1500;
$(buttonArray[i]).hover(function() {
//This will stop any animations if the user scrolls.
htmlBody.bind("scroll mousedown DOMMouseScroll mousewheel keyup", function(e)
{
if ( e.which > 0 || e.type === "mousedown" || e.type === "mousewheel"){
htmlBody.stop().unbind('scroll mousedown DOMMouseScroll mousewheel keyup');
}
});
var link = $(groupArray[i-1]);
var offset = link.offset();
var top2 = offset.top;
var left = offset.left;
var bottom = top2 + $(groupArray[i-1]).outerHeight();
//bottom = Math.abs(bottom - offset.top);
var right = $(window).width() - link.width();
right = Math.abs(offset.left - right);
var scrollDuration = 0;
if (inRange($(buttonArray[i]).offset().top, $(groupArray[i-1]).position().top, bottom))
{
//console.log("fast");
scrollDuration = 500;
//$(group).addClass("hoverYear");
}
else if ($(buttonArray[i]).offset().top <= $(groupArray[i-1]).offset().top && allButtonArray.length == 1)
{
//console.log("fast");
scrollDuration = 500;
//$(group).removeClass("hoverYear");
}
else if ($(buttonArray[i]).offset().top > 495 && $(buttonArray[i]).offset().top < 1700 && !inRange($(buttonArray[i]).offset().top, $(groupArray[i-1]).position().top, bottom))
{
scrollDuration = 1000;
//console.log("slow");
//$(group).removeClass("hoverYear");
}
else if ($(buttonArray[i]).offset().top > 1701 && $(buttonArray[i]).offset().top < 3000 && !inRange($(buttonArray[i]).offset().top, $(groupArray[i-1]).position().top, bottom))
{
scrollDuration = 1500;
//console.log("slower");
//$(group).removeClass("hoverYear");
}
else if ($(buttonArray[i]).offset().top > 3001 && $(buttonArray[i]).offset().top < 6000 && !inRange($(buttonArray[i]).offset().top, $(groupArray[i-1]).position().top, bottom))
{
scrollDuration = 2000;
//console.log("much slower");
//$(group).removeClass("hoverYear");
}
else if ($(buttonArray[i]).offset().top > 6001 && !inRange($(buttonArray[i]).offset().top, $(groupArray[i-1]).position().top, bottom))
{
scrollDuration = 2500;
console.log("the slowest");
//$(group).removeClass("hoverYear");
}
else
{
scrollDuration = 500;
}
//to prevent the various hover states to take control when the button isn't floating
if (!($(buttonArray[i])).hasClass("float"))
{
scrollDuration = 0;
console.log("doesnt have class")
}
// on mouse in, start a timeout
timer = setTimeout(function() {
//the delay for the hover scroll feature
htmlBody.animate({scrollTop: $(groupArray[i-1]).offset().top}, scrollDuration, 'easeInOutCubic');
}, delay);
}, function() {
// on mouse out, cancel the timer
clearTimeout(timer);
});
$.each(allButtonArray, function(j, val){
$(allButtonArray[j]).appendTo(closeBar);
console.log(allButtonArray.length);
arrowDown.show();
arrowUp.show();
arrowDown.prependTo(closeBar);
arrowUp.appendTo(closeBar);
//Changes the width of the buttons based upon how many are on the screen
if (allButtonArray.length > 7)
{
$("float").css('width', '7%');
$(val).css('width', '7%');
$(allButtonArray[0]).css('width','7%');
allButtonArray.sort(sortElements);
//console.log(val);
}
else if (allButtonArray.length <= 7)
{
$(val).css("width", '10%');
$("float").css("width", '10%');
allButtonArray.sort(sortElements);
//console.log(val);
}
});
}
if ($(groupArray[i-1]).height() == 0)
{
$(buttonArray[i]).css("width", '50%');
allButtonArray.splice(allButtonArray.indexOf($(buttonArray[i])), 1);
console.log(allButtonArray.length);
$(closeBarArray[i]).show();
$(buttonArray[i]).appendTo($(closeBarArray[i]));
arrowDown.show();
arrowUp.show();
arrowDown.prependTo(closeBar);
arrowUp.appendTo(closeBar);
}
if (group2001.height() == 0 && group2002.height() == 0 && group2003.height() == 0 && group2004.height() == 0 && group2005.height() == 0 && group2006.height() == 0 && group2007.height() == 0
&& group2008.height() == 0 && group2009.height() == 0 && group2010.height() == 0 && group2011.height() == 0 && group2012.height() == 0)
{
$(closeBarArray[i]).removeClass("floatCloseBar");
htmlBody.animate({scrollTop: revealAllButton.offset().top - 75}, 500);
arrowDown.hide();
arrowUp.hide();
//console.log($(document).height() + " the current height");
}
});
$(buttonArray[i]).toggleClass("openClose");
$(buttonArray[i]).toggleClass("openClose2");
});
});
function inRange(x, min, max){
return (x >= min && x <= max);
}
If you would like a reference to what worked previously, I could post that code. It is much more bulky and much less organized. I've tried many different things to eliminate the bug but I'm at a loss. My knowledge of JS scope is limited.
And thanks for any help, it is very much appreciated.

attachEvent and addEvent render unexpected result

I guess I must have made some amateur mistake that I keep on overlooking, but I can't seem to figure it out.
I'm making a onepage smoothscrolling website. If you scroll, the browser detects the direction and then scrolls you to the appropriate div. However when I scroll, an incorrect pagenumber is passed every time.
Here's the relevant javacript code:
var mousewheelevt;
var wheeldirection;
var wheeldirectiontype;
function ScrollToPage(pageNumber, directionNumber, directionNumberType) {
console.log('pageNumber: ' + pageNumber);
var direction;
var newPageNumber;
var directionType; //0=up, 1=down
console.log('directionNumberType: ' + directionNumberType);
console.log('directionNumber: ' + directionNumber);
if (directionNumberType == 0){
//non ff
if (directionNumber > 0) {
directionType = 0; //up
} else {
directionType = 1; //down
}
} else {
//ff
if (directionNumber < 0) {
directionType = 0; //up
} else {
directionType = 1; //down
}
}
console.log('directionType: ' + directionType);
console.log('pageNumber: ' + pageNumber);
if (directionType == 0) {
direction = 'up';
if(pageNumber > 1) {
newPageNumber = pageNumber - 1;
} else {
newPageNumber = 1
}
} else {
direction = 'down';
if(pageNumber < 5) {
newPageNumber = pageNumber + 1;
} else {
newPageNumber = 5;
}
}
$.scrollTo( $('#Page_' + newPageNumber), 800);
console.log(direction + ' - ' + newPageNumber);
}
$(document).ready(function() {
var y;
if(/Firefox/i.test(navigator.userAgent)) {
mousewheelevt = "DOMMouseScroll";
wheeldirectiontype = 1;
} else {
mousewheelevt = "mousewheel"; //FF doesn't recognize mousewheel as of FF3.x
wheeldirectiontype = 0;
}
for (y = 1; y <= 5; y++) {
console.log(y);
if (document.attachEvent) {//if IE (and Opera depending on user setting)
if(wheeldirectiontype == 0) {
document.getElementById('Page_' + y).attachEvent("on"+mousewheelevt, function(e){ScrollToPage(y, w.wheelDelta, wheeldirectiontype)});
} else {
document.getElementById('Page_' + y).attachEvent("on"+mousewheelevt, function(e){ScrollToPage(y, e.detail, wheeldirectiontype)});
}
} else if (document.addEventListener) {//WC3 browsers
if(wheeldirectiontype == 0) {
document.getElementById('Page_' + y).addEventListener(mousewheelevt, function(e){ScrollToPage(y, e.wheelDelta, wheeldirectiontype)}, false);
} else {
document.getElementById('Page_' + y).addEventListener(mousewheelevt, function(e){ScrollToPage(y, e.detail, wheeldirectiontype)}, false);
}
}
console.log(y);
$("#Page_" + y).wipetouch({
wipeUp: function(result) {ScrollToPage(y,1,0);},
wipeDown: function(result) {ScrollToPage(y,0,0);}
});
}
});
and here's the html:
<body>
<div id="Page_1" class="Landscape">
Ankerrui 2
</div>
<div id="Page_2" class="Landscape">
Voorwoord
</div>
<div id="Page_3" class="Landscape">
Beschrijving
</div>
<div id="Page_4" class="Landscape">
In de buurt
</div>
<div id="Page_5" class="Landscape">
Foto's
</div>
</body>
the page loads right on the first page, when I scroll down it scrolls to the bottom page wih the console showing 6 as the pageNumber. When I scroll back up, it stays on the last page, with the console showing 6 as the pageNumber as well. This is right if the pageNumber would actually be 6, but it should be respectively 1 and 5.
The console does show the right values for the y variable that is used to add the attachEvents, so I'm a bit clueless here.

Categories