Pure JavaScript Slideshow Play/Pause with Spacebar - javascript

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>

Related

my character is not moving left or right. I cannot find the problem

So I am following a tutorial from internet for a game. The problem is my character is not moving left or right. Here is the code:
var character = document.getElementById("character");
var interval;
var both = 0;
function moveLeft() {
var left = parseInt(window.getComputedStyle(character).getPropertyvalue("left"));
character.style.left = left - 2 + "px";
}
function moveRight() {
var left = parseInt(window.getComputedStyle(character).getPropertyvalue("left"));
character.style.left = left + 2 + "px";
}
document.addEventListener("keydown", event => {
if (both == 0) {
both++;
if (event.key === "ArrowLeft") {
interval = setInterval(moveLeft, 1);
}
if (event.key === "ArrowRight") {
interval = setInterval(moveRight, 1);
}
}
});
document.addEventListener("keyup", event => {
clearInterval(interval);
both = 0;
});
<div id="game">
<div id="character"></div>
</div>
getPropertyvalue, like most names in js should have capital letters for every new word after the first (camel case),
Change it to getPropertyValue :)
var character = document.getElementById("character");
var interval;
var both = 0;
function moveLeft() {
var left = parseInt(window.getComputedStyle(character).getPropertyValue("left"));
character.style.left = left - 2 + "px";
}
function moveRight() {
var left = parseInt(window.getComputedStyle(character).getPropertyValue("left"));
character.style.left = left + 2 + "px";
}
document.addEventListener("keydown", event => {
if (both == 0) {
both++;
if (event.key === "ArrowLeft") {
interval = setInterval(moveLeft, 1);
}
if (event.key === "ArrowRight") {
interval = setInterval(moveRight, 1);
}
}
});
document.addEventListener("keyup", event => {
clearInterval(interval);
both = 0;
});
Also, make sure your style is position:absolute
<div id="game">
<div id="character" style="position:absolute;"></div>
</div>
Of course this should be in css

Display javaScript variable value on HTML page?

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.

Javascript with jQuery for slider. Strange loop

This is a script that I'm using for a slider. In this slider I've 2 button left and right for visit the slides. I've used jQuery and a bit of Javascript for do this. I'm using a button for play/pause but after the 3rd time the slider crash and it goes really fast.
The button
<input type="button" class="pausa" value="PAUSE" />
The script
$(document).ready(function(){
var one = "label#arrow-";
var x = 2;
var y = 0;
var two = ".arrows";
function clickin() {
if(jQuery('.pausa').data('clicked')) {
jQuery('.pausa').click(function(){
$(this).data('clicked', false);
$(this).val('PAUSE');
return setTimeout(clickin, 4000);
});
}
else {
while ((x != 7) && (y == 0)) {
$(one + x + two).trigger('click');
x++;
if (x != 7)
return setTimeout(clickin, 4000);
}
if (x == 7) {
y = 1;
x = 5;
}
while ((x != 0) && (y == 1)) {
$(one + x + two).trigger('click');
x--;
if (x != 7)
return setTimeout(clickin, 4000);
}
if (x == 0) {
y = 0;
x = 2;
return setTimeout(clickin, 4000);;
}
}
}
setTimeout(clickin, 4000);
jQuery('.pausa').click(function(){
$(this).data('clicked', true);
$(this).val('PLAY');
return clickin();
});
});
I've fixed it:
You can check the complete code here
$(document).ready(function(){
var one = "label#arrow-";
var two = ".arrows";
var x = 2; //Value of the button
var point = 0; //Check if you are pressing for play or pause
function clickin() {
if(point % 2)
$('.pausa').val('PLAY'); //Rotation Pause
else
$('.pausa').val('PAUSA'); //Rotation Play
if(!(point % 2)) //If it's in Play (Pause for button)
{
$(one + x + two).trigger('click');
x++;
if(x == 7)
x = 1;
return setTimeout(clickin, 4000)
}
else return 1; //If it's in Pause (Play for button)
}
setTimeout(clickin, 4000);
jQuery('.pausa').click(function(){ //Waiting input click
point++;
return clickin()
});
});

setInterval De incrementing countdown does not stop at Zero

I am busy making a Red Or blue clicking game which can be viewed here: http://www.ysk.co.za/red-blue
My problem is the countdown I have made by de incrementing var countdown only stops when the function key() is run, and until it is run the countdown goes into negative values if more than 12 seconds
My Javascript is:
var i = 0;
var seconds = 0;
var countdown = 12;
setInterval(function () {
$("#counter").html(countdown.toFixed(2));
}, 10);
function play() {
$("#num").select();
}
function key(e) {
var code = e.keyCode ? e.keyCode : e.charCode;
var random = Math.random();
if (random <= 0.5) {
$("#RedBlue").css("background-color", "red")
} else {
$("#RedBlue").css("background-color", "blue")
}
if (code === 86) {
$("#red").css("background", "#ff4e00");
setTimeout(function () {
$("#red").css("background-color", "red")
}, 500);
var color = "rgb(255, 0, 0)";
} else if (code === 66) {
$("#blue").css("background-color", "#006bff");
setTimeout(function () {
$("#blue").css("background-color", "blue")
}, 500);
color = "rgb(0, 0, 255)";
}
var score = i / seconds;
var Endscore = (i - 1) / seconds;
if ($("#RedBlue").css("background-color") != color) {
alert("You clicked " + i + " times in " + seconds.toFixed(2) + " seconds. your score was " + score.toFixed(2));
document.location.reload(true);
} else if ($("#RedBlue").css("background-color") == color) {
$("#score").html("");
i++;
}
if (i == 1) {
setInterval(function () {
seconds += 0.01
}, 10);
setInterval(function () {
countdown -= 0.01
}, 10);
};
if (countdown < 0) {
alert("You clicked " + (parseInt(i) - 1) + " times in 12 seconds. your score was " + Endscore.toFixed(2));
document.location.reload(true);
}
}
My HTML is:
<div id="game">
<div id="RedBlue"></div>
<div id="red" style="background:red;"></div>
<div id="blue" style="background:blue;"></div><div class="clear"></div>
<button onclick="play()">start</button><br>Enter "v" if the block is red or "b" if the block is blue
<input type="text" size="2" maxlength="1" id="num" onkeyup="key(event); this.select()" />
</div>
<div id="counter" style="font-family:monospace;font-size:100px;font- weight:600;float:left;margin-left:40px;"></div>
<div id="score"></div>`
How Can I do this so that when countdown == 1 the alert() appears, also if you know of any better way to stop and reset the game other than refreshing the page that would be great.
Your help is much appreciated
Since you are updating your time in the setInterval, you should check in there whether the countdown value has reached 0
setInterval(function () {
countdown -= 0.01;
if (countdown < 0) {
alert("You clicked " + (parseInt(i) - 1) + " times in 12 seconds. your score was " + Endscore.toFixed(2));
document.location.reload(true);
}
}, 10);

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