document get element not executing in my begin game function - javascript

For some reason when I try to change the src element in the begin game function it does not want to change. The src location is correct and I've tried the setTimeout as well. Is there a way to pause the code but for it to run it Synchronized? The begin function is below pasted again to make it easier to view. Is there a way to use setTimeout without it running EVERYTHING at once?
HTML:
<html>
<head>
<script src="scripts/simon.js" async></script>
<link rel="stylesheet" href="scripts/simon.css">
</head>
<body>
<div id="mySidenav" class="sidenav">
×
<h1><u>Difficulty</u></h1>
Easy
Medium
Hard
Xtreme
<button id="start" onclick="startup()">Start</button>
</div>
<span style="font-size:30px;cursor:pointer" onclick="openNav()">☰</span>
<div class="infoBar">
<img src="assets/icons/nothing.png"></img>
<img src="assets/icons/nothing.png"></img>
<img src="assets/icons/nothing.png"></img>
<img src="assets/icons/nothing.png"></img>
<img src="assets/icons/nothing.png"></img>
</div>
<div class="game-container">
<img class="redButton" id="red" src="assets/icons/red.png"></img>
<img class="blueButton" id="blue" src="assets/icons/blue.png"></img>
<img class="greenButton" id="green" src="assets/icons/green.png"></img>
<img class="yellowButton" id="yellow" src="assets/icons/yellow.png"></img>
<div class="logo">
<img class="logoButton" src="assets/icons/logo.png"></img>
</div>
</div>
<script src="scripts/simon.js"></script>
</body>
</html>
JS:
var currentLvl;
var playerinput;
var levelOfDiff = 0;
function sleep(miliseconds){
var currentDate = new Date();
var currentTime = currentDate.getTime();
while (currentTime + miliseconds >= new Date().getTime()){
}
}
function openNav() {
document.getElementById("mySidenav").style.width = "250px";
}
function closeNav() {
document.getElementById("mySidenav").style.width = "0";
document.getElementById("start").innerHTML = "Start";
}
function setDifficulty(diff){
if(diff == "Easy"){
document.getElementById("start").innerHTML = "Start Easy Mode";
levelOfDiff = 3;
}
if(diff == "Medium"){
document.getElementById("start").innerHTML = "Start Medium Mode";
levelOfDiff = 5;
}
if(diff == "Hard"){
document.getElementById("start").innerHTML = "Start Hard Mode";
levelOfDiff = 7;
}
if(diff == "Xtreme"){
document.getElementById("start").innerHTML = "Start Xtreme Mode";
levelOfDiff = 10;
}
}
function startup(){
if(levelOfDiff != 0){
var mainSequence = [levelOfDiff];
beginGame(mainSequence);
}
else{
alert("Please choose a difficulty");
}
}
function beginGame(mainSequence){
for(var x = 0;x<levelOfDiff;x++){
mainSequence[x] = Math.ceil(Math.random() * Math.ceil(4));
}
console.log(mainSequence);
for(var y=0;y<levelOfDiff;y++){
if(mainSequence[y] == 1){
console.log("change");
document.getElementById("green").src = "../assets/icons/greenClick.png";
sleep(1000);
console.log("back");
document.getElementById("green").src = "../assets/icons/green.png";
}
if(mainSequence[y] == 2){
console.log("change");
document.getElementById("red").src = "../assets/icons/redClick.png";
sleep(1000);
console.log("back");
document.getElementById("red").src = "../assets/icons/red.png";
}
if(mainSequence[y] == 3){
console.log("change");
document.getElementById("blue").src = "../assets/icons/BlueClick.png";
sleep(1000);
console.log("back");
document.getElementById("blue").src = "../assets/icons/blue.png";
}
if(mainSequence[y] == 4){
console.log("change");
document.getElementById("yellow").src = "../assets/icons/yellowClick.png";
sleep(1000);
console.log("back");
document.getElementById("yellow").src = "../assets/icons/yellow.png";
}
sleep(1000);
}
}
/*
Green is 1
Red is 2
Blue is 3
Yellow is 4
*/
Problem in JS
function beginGame(mainSequence) {
for (var x = 0; x < levelOfDiff; x++) {
mainSequence[x] = Math.ceil(Math.random() * Math.ceil(4));
}
console.log(mainSequence);
for (var y = 0; y < levelOfDiff; y++) {
if (mainSequence[y] == 1) {
console.log("change");
document.getElementById("green").src = "../assets/icons/greenClick.png";
sleep(1000);
console.log("back");
document.getElementById("green").src = "../assets/icons/green.png";
}
if (mainSequence[y] == 2) {
console.log("change");
document.getElementById("red").src = "../assets/icons/redClick.png";
sleep(1000);
console.log("back");
document.getElementById("red").src = "../assets/icons/red.png";
}
if (mainSequence[y] == 3) {
console.log("change");
document.getElementById("blue").src = "../assets/icons/BlueClick.png";
sleep(1000);
console.log("back");
document.getElementById("blue").src = "../assets/icons/blue.png";
}
if (mainSequence[y] == 4) {
console.log("change");
document.getElementById("yellow").src = "../assets/icons/yellowClick.png";
sleep(1000);
console.log("back");
document.getElementById("yellow").src = "../assets/icons/yellow.png";
}
sleep(1000);
}
}
/*
Green is 1
Red is 2
Blue is 3
Yellow is 4
*/

You've stumbled on one of the differences between JS and most other well-known programming languages. In JavaScript, everything in the same scope runs at the same time. Therefore sleep(1000) doesn't actually do anything because it just runs alongside everything else without blocking.
I'd recommend looking into promises, but if I understand your needs correctly, setTimeout could work. Try something like this:
// This line will run
document.getElementById("green").src = "../assets/icons/greenClick.png";
// Then this will set a waiting time of one second
setTimeout(function() {
// This line will run after 1 second
document.getElementById("green").src = "../assets/icons/green.png";
},1000)

Related

How to increase counter when the correct image is clicked

I have written in HTML and Javascript a webpage that cycles through an image of a lion and a frog. I have set 2 buttons to start and stop the images from cycling every 500ms. My problem is I am unsure how to go around creating a score function that counts the number of times a specific image is clicked. For example, if the frog image is clicked I want the score to +1 and if the lion image is clicked I want the score to -1.
Here is my code.
<html>
<head>
<title>Question 2</title>
<script>
var images = ["frog.jpg", "lion.jpg"] //I Created an array with both images inside
var imgInterval;
var imgi = 'empty';
var score = document.getElementById('score');
function start(){
imgInterval = setInterval(displayImage, 500); //Sets an interval for the func displayImage and for it to loop ever 500ms
}
function displayImage() {
if (imgi == 'empty') { //If the index is empty set the interval to 0 or frog.jpg
imgi = 0;
} else if (imgi == 0) { // If the index is set to 0 set it to 1 or lion.jpg
imgi = 1;
} else if (imgi == 1) { // If the idex is set to 1 set it back to 0, this creates a loop that will be run every 500ms
imgi = 0;
}
document.getElementById('image').src = images[imgi];
}
function stop(){
clearInterval(imgInterval);
}
function scoreNumb() { //This is where i think i am having issues and am unsure what to do.
if (imgi.onclick == 0) {
score + 1;
}
}
</script>
</head>
<body>
<button onclick=start()>Start Animation</button>
<button onclick=stop()>Stop Animation</button>
<br/> <br/>
<span>
<img id="image" onclick=scoreNumb() width="250px" />
</span>
<br/>
<span id="score">0</span>
</body>
</html>
replace your function scoreNumb with mine
<script>
...
var score = document.getElementById('score');
var valueScore = 0; /*created this*/
...
function scoreNumb() { //This is where i think i am having issues and am unsure what to do.
/*if (imgi.onclick == 0) {
score + 1;
}*/
/*0 = frog AND 1 = lion*/
if (imgi == 0){/*+1*/
valueScore++;
}else {
valueScore--;
}
console.log("click", valueScore);
document.getElementById('score').textContent = valueScore;
}
You are nearly there. You just need to check which image was clicked by checking the img src
If the image src is lion then you can increase the totalScore count variable update the count as well using textContent method.
function scoreNumb(e) {
if (e.getAttribute('src') == 'https://via.placeholder.com/150') {
totalScore++
} else {
totalScore--
}
score.textContent = totalScore
}
Working Demo:
var images = ["https://via.placeholder.com/150", "https://via.placeholder.com/200"] //I Created an array with both images inside
var imgInterval;
var imgi = 'empty';
var score = document.getElementById('score');
var totalScore = 0
function start() {
imgInterval = setInterval(displayImage, 1000); //Sets an interval for the func displayImage and for it to loop ever 500ms
}
function displayImage() {
if (imgi == 'empty') { //If the index is empty set the interval to 0 or frog.jpg
imgi = 0;
} else if (imgi == 0) { // If the index is set to 0 set it to 1 or lion.jpg
imgi = 1;
} else if (imgi == 1) { // If the idex is set to 1 set it back to 0, this creates a loop that will be run every 500ms
imgi = 0;
}
document.getElementById('image').src = images[imgi];
}
function stop() {
clearInterval(imgInterval);
}
function scoreNumb(e) { //This is where i think i am having issues and am unsure what to do.
if (e.getAttribute('src') == 'https://via.placeholder.com/150') {
totalScore++
} else {
totalScore--
}
score.textContent = totalScore
}
<html>
<head>
<title>Question 2</title>
<script>
</script>
</head>
<body>
<button onclick=start()>Start Animation</button>
<button onclick=stop()>Stop Animation</button>
<br /> <br />
<span>
<img id="image" onclick=scoreNumb(this) width="250px" />
</span>
<br />
<span id="score">0</span>
</body>
</html>
Change this variable declaration from:
let score = document.getElementById('score');
to this:
let score = 0;
then in the function named scoreNumb() change the following :
if (imgi.onclick == 0) {
score + 1;
}
to this :
if (imgi === 0) {
score += 1;
}
else{
score -= 1;
}
// Here you can update your html code with getElementById.
console.log(score)

How to add link only one specific page?

I would like to add a link just one page out of all the pages. I've tried some different ways, but that is not working and closing the image slide simultaneously.
var photo = ["image/pic0.jpg", "image/pic1.jpg", "image/pic2.jpg", "image/pic3.jpg", "image/pic4.jpg"];
var imgTag = document.querySelector(".slide-pic");
var count = 0;
var time = 0;
window.onload = function() {
setTimeout(next, 5000);
};
function next() {
count++;
if (count >= photo.length) {
count = 0;
imgTag.src = photo[count];
} else {
imgTag.src = photo[count];
}
}
function prev() {
count--;
if (count < 0) {
count = photo.length - 1;
imgTag.src = photo[count];
} else {
imgTag.src = photo[count];
}
}
<div class="front-pic">
<button class="left-btn" onclick="prev()"><i class="fa fa-arrow-left"></i></button>
<img id="pic-link" class="slide-pic" src="image/pic0.jpg">
<button class="right-btn" onclick="next()"><i class="fa fa-arrow-right"></i></button>
</div>
I'm not sure what exactly you were trying to achieve but I still gave it a try. Try the code snippet below and see if it works for you.
var photo = [
"https://image.shutterstock.com/image-photo/pacific-coast-highway-101-oregon-600w-1340723072.jpg",
"https://image.shutterstock.com/image-photo/cargo-train-departing-station-during-600w-1153325710.jpg",
"https://image.shutterstock.com/image-photo/california-united-states-pacific-coast-600w-322331276.jpg",
"https://image.shutterstock.com/image-photo/piha-beach-on-west-coast-600w-154908542.jpg",
"https://image.shutterstock.com/image-photo/sea-cliff-bridge-along-grand-600w-167705717.jpg"
];
var imgTag = document.querySelector(".slide-pic");
var count = 0;
var time = 0;
window.onload = function () {
setTimeout(next, 5000);
};
function next() {
count++;
if (count >= photo.length) {
count = 0;
imgTag.src = photo[count];
}
else {
imgTag.src = photo[count];
}
}
function prev() {
count--;
if (count < 0) {
count = photo.length - 1;
imgTag.src = photo[count];
}
else {
imgTag.src = photo[count];
}
}
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<div class="front-pic">
<button class="left-btn" onclick="prev()"><i class="fa fa-arrow-left"></i></button>
<img id="pic-link" class="slide-pic" width="200" height="200" src="https://image.shutterstock.com/image-photo/summer-landscape-blue-sky-on-600w-313318763.jpg">
<button class="right-btn" onclick="next()"><i class="fa fa-arrow-right"></i></button>
</div>
Please note the changes that I made in the original code.
I'm using / in the path of the images rather than \.
Changed the images. These are available online and were added only for the purpose of demonstration. You, of course, can give the path to your images. But, when you give a path to a static file, give a relative path instead of absolute.
I added font-awesome CDN, as I noticed you were using it for the icons in the buttons. You can change this one with the one you're currently using.

I created a Stopwatch in JavaScript. I would like to add a sound when a user inputs the time to be reminded

I am a newbie and trying to learn. I created a Start-stop watch in HTML and js. I would like to add an input field for the users to input time and when it hits that a sound should be played.
I tried to make a variable and try to get the input data but I only screw up everything. I tried to look for it on YouTube and Google but I couldn't seem to find any answers.
Thanks for your time. Below is my code.
<div class="controls">
<button onclick="start()">Start</button>
<button onclick="pause()">Pause</button>
<button onclick="stop()">Stop</button>
<button onclick="restart()">Restart</button>
<button onclick="lap()">Lap</button>
<button onclick="resetLaps()">Reset Laps</button>
</div>
<div class="stopwatch">
00:00:00
</div>
<input type="text" id="inputVal"><button onclick="getVal()">Set Time</button>
<ul class="laps"></ul>
<audio id="ado" src="http://static1.grsites.com/archive/sounds/musical/musical009.mp3" controls="true"></audio>
Below is the Javascript.
<script type="text/javascript">
var ms = 0, s = 0, m = 0;
var timer;
var stopwatchEL = document.querySelector('.stopwatch');
var lapsContainer = document.querySelector('.laps');
function start(){
if(!timer){
timer = setInterval(run, 10)
}
}
function run(){
stopwatchEL.textContent = getTimer();
ms++;
updateTimer();
if(ms == 100){
ms = 00;
s++
}
if(s == 60){
s = 0;
m++;
}
}
function pause(){
stopTimer();
}
function stop(){
stopTimer();
m = 0;
ms = 0;
s = 0;
stopwatchEL.textContent = getTimer();
}
function getTimer(){
return (m < 10 ? "0" + m:m) + ":" + (s < 10 ? "0" + s:s) + ":" + (ms < 10 ? "0" + ms:ms);
}
function stopTimer(){
clearInterval(timer);
timer = false;
}
function restart(){
stop();
start();
}
function lap(){
if(timer){
var li = document.createElement('li');
li.innerText = getTimer();
lapsContainer.appendChild(li);
}
}
function resetLaps() {
lapsContainer.innerHTML = "";
}
function getVal(){
var inputVal = document.getElementById('inputVal').value;
}
function updateTimer() {
if(m == 0, ms == 0, s == inputVal){
$('#ado').get(0).play();
pause();
}
}
</script>
Thanks again.
First you need inputVal globally as #Denhell mentioned.
var inputVal = Number.POSITIVE_INFINITY;
function getVal(){
inputVal = document.getElementById('inputVal').value;
}
Second your function updateTimer needs a comparison between your inputVal and the actual time of the timer. For playing the sound I transferred your jQuery-code to vanilla JS.
function updateTimer() {
if(getTimer() == inputVal){
document.getElementById('ado').play();
pause();
}
}
In the function run the call of the updateTimer has to be executed at the end because otherwise the value for the comparison doesn't function right at the beginning of a new second or minute (e.g. 00:13:00).
function run(){
stopwatchEL.textContent = getTimer();
ms++;
if(ms == 100){
ms = 0;
s++;
}
if(s == 60){
s = 0;
m++;
}
updateTimer();
}
The only thing is, that the timer stops right but do not update the last ms. For this you could look yourself. For my solution it is necessary that the manually set time is at the format mm:ss:ms with all three values as a 2-digit value like 01:17:09
You can try it here: https://jsfiddle.net/8w67uy5a/5/
You are declaring a variable inputVal inside a getVal function that other functions don't know about it.
Use something like this
var inputVal = Number.POSITIVE_INFINITY;
function getVal(){
inputVal = document.getElementById('inputVal').value;
}
This will fix your problem.
<audio id="ado">
<source src="http://static1.grsites.com/archive/sounds/musical/musical009.mp3" type="audio/mpeg"></source>
</audio>
function getVal() {
const sound = document.getElementById("ado");
sound.play();
var inputVal = document.getElementById("inputVal").value;
}

Quit Application in Java Script?

i need to quit application as soon as stop button pressed from HTML.The start and stop button working fine but the problem with stop button is that it pause the game not quit the application. i wrote this code in else block window.setTimeout(animloop, 1000); it will pause the game but not quit the game or if i use windows.close() it will close browser immediately .
my code:
var gameStarted = false;
// 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
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>
<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 -->
</body>
</html>
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++) {
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;
}
What does "quit the application" mean?
You can close the browser window, or redirect the user to another route.
But the exact semantics of "quit the application" for your game in the browser need to be defined.
If you mean "Close the web browser", then you need to have your game open in a new window from the game code when it starts, so that it can close the window when it finishes.
So you have a launcher page, and that opens the game in a new window. You can then communicate between the windows, and close the child window later.
See here for an example of opening a child window. And here for closing it. And here for communicating between them.

javascript code of an image rotator

I am trying to make an 8 image button rotator via javascript, I have buttons "<" ">" "<<" ">>" and a check box image rotator. I can send my code so far and screenshot, can someone help? here is my code.
<div id="images">
<img src="images/sample1.jpg" id="image"/>
</div>
<div id="buttonContainer">
<button id="firstImageButton" title="Click to view the first image." onClick="previousImage("image")">«</button>
<button id="previousImageButton" title="Click to view the previous image." ><</button>
<button id="nextImageButton" title="Click to view the next image." >></button>
<button id="lastImageButton" title="Click to view the last image." onClick="images/sample8.jpg">»</button>
<br/><input type="checkbox" id="autoRotate" /><label for="autoRotate">Click to auto-rotate</label>
</div>
</div>
</div>
script
<script>
var images = [ "images/sample1.jpg", "images/sample2.jpg", "images/sample3.jpg", "images/sample4.jpg", "images/sample5.jpg", "images/sample6.jpg", "images/sample7.jpg", "images/sample8.jpg" ]
var currentImageIndex = 0;
var currentImage = 0;
function nextImageButton() {
currentImage += 1;
displayImage(currentImage);
}
function previousImageButton() {
currentImage -= 1;
displayPage(currentImage);
}
function displayImage (imageIndex) {
document.getElementById("images").innerHTML = images[imageIndex];
document.getElementById("nextImageButton").style.visibility = "visible";
document.getElementById("previousImageButton").style.visibility = "visible";
if(imageIndex == images.length - 1) {
document.getElementById("nextImageButton").style.visibility = "hidden";
}
if(imageIndex == 0) {
document.getElementById("previousImageButton").style.visibility = "hidden";
}
}
</script>
change all tabs before posting.
create a jsfiddle.net with the code.
what's with the </div></div></div> ?
what is onClick="images/sample8.jpg" supposed to do?
you have the same quotes in the onclick - if you wrap quotes you need to do ="...('xxx');"
document.getElementById("images").innerHTML = images[imageIndex];
should be document.getElementById("image").src = images[imageIndex];
Live Demo
var images = [ "http://lorempixel.com/output/food-q-c-640-480-1.jpg",
"http://lorempixel.com/output/food-q-c-640-480-2.jpg",
"http://lorempixel.com/output/food-q-c-640-480-3.jpg",
"http://lorempixel.com/output/food-q-c-640-480-4.jpg",
"http://lorempixel.com/output/food-q-c-640-480-5.jpg",
"http://lorempixel.com/output/food-q-c-640-480-6.jpg",
"http://lorempixel.com/output/food-q-c-640-480-7.jpg" ]
var tId,currentImage = 0;
function changeImage(dir) {
if (dir === 0) currentImage = 0; // first image
else if (dir===images.length-1) currentImage=images.length-1; // last image
else currentImage+=dir*1; // next or previous
if (currentImage<0 || currentImage>=images.length) currentImage=0; // will wrap
displayImage(currentImage);
}
function displayImage (imageIndex) {
window.console && console.log(imageIndex); // remove when happy
// document.getElementById("msg").innerHTML=(imageIndex+1)+"/"+images.length;
document.getElementById("image").src = images[imageIndex];
document.getElementById("nextImageButton").style.visibility=(imageIndex<images.length-1)?"visible":"hidden";
document.getElementById("previousImageButton").style.visibility=(imageIndex>0)?"visible":"hidden";
}
function rotate() {
changeImage(+1);
}
window.onload=function() {
document.getElementById("autoRotate").onclick=function() {
if (this.checked) tId=setInterval(rotate,3000)
else clearInterval(tId);
}
document.getElementById("firstImageButton").onclick=function() { changeImage(0) }
document.getElementById("lastImageButton").onclick=function() { changeImage(images.length-1) }
document.getElementById("nextImageButton").onclick=function() { changeImage(1) }
document.getElementById("previousImageButton").onclick=function() { changeImage(-1) }
}

Categories

Resources