How to pulse an image and change the rate of pulsing? - javascript

I think this is working but not really. I also don't think that it is the best approach.
The timer serves as another function running while having the ability to change the pulsing rate of the image.
I have tried to use gifs instead of because they have different speeds, there isn't a smooth transition when switching between images.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript" src="https://code.jquery.com/jquery-latest.js"></script>
<style>
#red-square {
position: absolute;
display: inline-block;
z-index: 1;
top : 200px;
right: 200px;
height: 100px;
width: 100px;
background-color: red;
}
</style>
</head>
<body>
<div id="result"></div>
<div id="red-square"></div>
<button onclick="speedOne();">speed one</button>
<button onclick="speedTwo();">speed two</button>
<button onclick="speedThree();">speed three</button>
<script>
var counter = 0,
stopTimeoutTwo = null,
stopTimeoutThree = null,
currentSpeed = "speed one";
function runCounter() {
counter++;
result.textContent = counter;
if(currentSpeed == "speed one") {
if((counter%60) == 0) {
$("#red-square").hide();
}else if((counter%60) != 0) {
$("#red-square").show();
}
}
else if(currentSpeed = "speed two") {
if((counter%45) == 0) {
$("#red-square").hide();
}else if((counter % 45) != 0) {
$("#red-square").show();
}
}else if(currentSpeed = "speed three") {
if((counter%30) == 0) {
$("#red-square").hide();
}else if((counter%30) != 0) {
$("#red-square").show();
}
}
if(counter < 1e5) timer = setTimeout(runCounter, 0);
}
runCounter();
function stepOne() {
currentSpeed = "speed one";
}
function stepTwo() {
currentSpeed = "speed two";
}
function stepThree() {
currentSpeed = "speed three";
}
</script>
</body>
</html>

You can use setInterval to create your efect like so: Fiddle!
This is the JS I used:
var speed = 4000;
var inter;
var square = document.getElementById("red-square");
square.style.backgroundColor = "red";
function myTime(){
inter = setInterval(function(){
console.log(square.style.backgroundColor+" "+speed);
if(square.style.backgroundColor == "red"){
square.style.backgroundColor = "blue";
}
else{
square.style.backgroundColor = "red";
}
}, speed);
}
function changSpeed(s){
clearInterval(inter);
speed = s;
inter=null;
myTime();
}
myTime();
the rest is your code.

Related

Creating timer in HTML by using setInterval and clearInterval in JS file to limit time

I want to limit how much time the player has to make their guesses using the setInterval and clearInterval methods but I am not sure on how to implement this feature. How could I achieve that?
I need to think carefully about when/where to start the timer, and when to clear it. I might also consider adding a display on the HTML page to show the user how much time they have left so can someone explain to me how to go about these steps?
PLEASE HELP
JS File:
const cluePauseTime = 333; //how long to pause in between clues
const nextClueWaitTime = 1000; //how long to wait before starting playback of the clue sequence
//Global variables
var clueHoldTime = 200; //how long to hold each clue's light/sound
// var pattern = [2, 3, 1, 4, 6, 1, 2, 4, 3, 5];
var pattern = [];
var clueLength = 10;
///////////////////////////////
var progress = 0;
var gamePlaying = false;
var tonePlaying = false;
var volume = 0.5;
var guessCounter = 0;
function startGame() {
progress = 0;
pattern = []; // reset so array doesn't get longer then 10 if we restart game
for (var i = 0; i < clueLength; i++) {
pattern.push(getRandomInt(5));
}
console.log("pattern: " + pattern);
gamePlaying = true;
document.getElementById("startBtn").classList.add("hidden");
document.getElementById("stopBtn").classList.remove("hidden");
playClueSequence();
}
function stopGame() {
gamePlaying = false;
document.getElementById("startBtn").classList.remove("hidden");
document.getElementById("stopBtn").classList.add("hidden");
}
function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max) + 1);
}
function lightButton(btn) {
document.getElementById("button" + btn).classList.add("lit");
}
function clearButton(btn) {
document.getElementById("button" + btn).classList.remove("lit");
}
function playSingleClue(btn) {
if (gamePlaying) {
lightButton(btn);
playTone(btn, clueHoldTime);
setTimeout(clearButton, clueHoldTime, btn);
}
}
function playClueSequence() {
guessCounter = 0;
let delay = nextClueWaitTime; //set delay to initial wait time
for (let i = 0; i <= progress; i++) {
// for each clue that is revealed so far
console.log("play single clue: " + pattern[i] + " in " + delay + "ms");
setTimeout(playSingleClue, delay, pattern[i]); // set a timeout to play that clue
delay += clueHoldTime;
delay += cluePauseTime;
}
}
function loseGame() {
stopGame();
alert("Game Over. You lost.");
}
function winGame() {
stopGame();
alert("Yayyyyy, you win!!");
}
function guess(btn) {
console.log("user guessed: " + btn);
if (!gamePlaying) {
return;
}
if (pattern[guessCounter] == btn) {
if (guessCounter == progress) {
if (progress == pattern.length - 1) {
winGame();
} else {
progress++;
playClueSequence();
}
} else {
guessCounter++;
}
//guessCounter++;
} else {
loseGame();
}
}
// Sound Synthesis Functions
const freqMap = {
1: 261.6,
2: 329.6,
3: 392,
4: 466.2,
5: 432.8,
6: 336.2
};
function playTone(btn, len) {
o.frequency.value = freqMap[btn];
g.gain.setTargetAtTime(volume, context.currentTime + 0.05, 0.025);
tonePlaying = true;
setTimeout(function() {
stopTone();
}, len);
}
function startTone(btn) {
if (!tonePlaying) {
o.frequency.value = freqMap[btn];
g.gain.setTargetAtTime(volume, context.currentTime + 0.05, 0.025);
tonePlaying = true;
}
}
function stopTone() {
g.gain.setTargetAtTime(0, context.currentTime + 0.05, 0.025);
tonePlaying = false;
}
//Page Initialization
// Init Sound Synthesizer
var context = new AudioContext();
var o = context.createOscillator();
var g = context.createGain();
g.connect(context.destination);
g.gain.setValueAtTime(0, context.currentTime);
o.connect(g);
o.start(0);
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Hello!</title>
<!-- import the webpage's stylesheet -->
<link rel="stylesheet" href="/style.css" />
<!-- import the webpage's javascript file -->
<script src="/script.js" defer></script>
</head>
<body>
<h1>Memory Game</h1>
<p>
Welcome to the game that will test your memory!
</p>
<button id="startBtn" onclick="startGame()">
Start
</button>
<button id="stopBtn" class="hidden" onclick="stopGame()">
Stop
</button>
<div id="gameButtonArea">
<button
id="button1"
onclick="guess(1)"
onmousedown="startTone(1)"
onmouseup="stopTone()"
></button>
<button
id="button2"
onclick="guess(2)"
onmousedown="startTone(2)"
onmouseup="stopTone()"
></button>
<button
id="button3"
onclick="guess(3)"
onmousedown="startTone(3)"
onmouseup="stopTone()"
></button>
<button
id="button4"
onclick="guess(4)"
onmousedown="startTone(4)"
onmouseup="stopTone()"
></button>
<button
id="button5"
onclick="guess(5)"
onmousedown="startTone(5)"
onmouseup="stopTone()"
></button>
<button
id="button6"
onclick="guess(6)"
onmousedown="startTone(6)"
onmouseup="stopTone()"
></button>
</div>
</body>
</html>
CSS:
body {
font-family: helvetica, arial, sans-serif;
margin: 2em;
background-color: slategrey;
color: white;
}
h1 {
font-family: verdana, arial, sans-serif;
color: yellow;
}
button {
padding: 15px;
border-radius: 15px;
}
#gameButtonArea > button {
width: 200px;
height: 200px;
margin: 2px;
}
.hidden {
display: none;
}
#button1 {
background: lightgreen;
}
#button1:active,
#button1.lit {
background: green;
}
#button2 {
background: lightblue;
}
#button2:active,
#button2.lit {
background: blue;
}
#button3 {
background: pink;
}
#button3:active,
#button3.lit {
background: red;
}
#button4 {
background: lightyellow;
}
#button4:active,
#button4.lit {
background: yellow;
}
#button5 {
background: lightgray;
}
#button5:active,
#button5.lit {
background: black;
}
#button6 {
background: white;
}
#button6:active,
#button6.lit {
background: purple;
}
Here is a jsFiddle with a possible solution, hope it helps: https://jsfiddle.net/arksyLxw/24/
Please note the only thing I couldn't get working with the limited time I had to work on this was a call to loseGame from within the myTimer function it is undefined due to the fact it is being call within a asynchronous function.
Edit: Nevermind it was a simple spelling error lol had LoseGame not loseGame
https://jsfiddle.net/ts25hyru/4/
const cluePauseTime = 333; //how long to pause in between clues
const nextClueWaitTime = 1000; //how long to wait before starting playback of the clue sequence
//Global variables
var countDownTimer;
var timeLimit = 6;
var currentTime;
var clueHoldTime = 200; //how long to hold each clue's light/sound
// var pattern = [2, 3, 1, 4, 6, 1, 2, 4, 3, 5];
var pattern = [];
var clueLength = 10;
///////////////////////////////
var progress = 0;
var gamePlaying = false;
var tonePlaying = false;
var volume = 0.5;
var guessCounter = 0;
function startGame() {
progress = 0;
pattern = []; // reset so array doesn't get longer then 10 if we restart game
for (var i = 0; i < clueLength; i++) {
pattern.push(getRandomInt(5));
}
console.log("pattern: " + pattern);
gamePlaying = true;
document.getElementById("startBtn").classList.add("hidden");
document.getElementById("stopBtn").classList.remove("hidden");
document.getElementById("timeDiv").classList.remove("hidden");
playClueSequence();
}
function stopGame() {
clearInterval(countDownTimer); // remember to clear interval to prevent memory leaks
gamePlaying = false;
document.getElementById("startBtn").classList.remove("hidden");
document.getElementById("stopBtn").classList.add("hidden");
}
function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max) + 1);
}
function lightButton(btn) {
document.getElementById("button" + btn).classList.add("lit");
}
function clearButton(btn) {
document.getElementById("button" + btn).classList.remove("lit");
}
function playSingleClue(btn) {
if (gamePlaying) {
lightButton(btn);
playTone(btn, clueHoldTime);
setTimeout(clearButton, clueHoldTime, btn);
}
}
function playClueSequence() {
console.log('Entered playClueSequence');
guessCounter = 0;
let delay = nextClueWaitTime; //set delay to initial wait time
for (let i = 0; i <= progress; i++) {
// for each clue that is revealed so far
console.log("play single clue: " + pattern[i] + " in " + delay + "ms");
setTimeout(playSingleClue, delay, pattern[i]); // set a timeout to play that clue
setTimeout(() => {
if (i === progress) {
// document.getElementById("timeDiv").classList.remove("hidden"); // might be useful for styling timer
console.log('played final clue ...');
currentTime = timeLimit; // this should reset every round
countDownTimer = setInterval(() => {
myTimer();
}, 1000);
}
}, delay);
delay += clueHoldTime;
delay += cluePauseTime;
}
console.log('sequence complete');
}
function myTimer() {
console.log('counting down');
currentTime = (currentTime - 1); // can also do currentTime --
if (currentTime <= 0) {
currentTime = 0;
document.getElementById("timeDiv").innerHTML = ('Time remaing: ' + currentTime);
clearInterval(countDownTimer);
loseGame();
}
document.getElementById("timeDiv").innerHTML = ('Time remaing: ' + currentTime);
}
function loseGame() {
stopGame();
alert("Game Over. You lost.");
}
function winGame() {
stopGame();
alert("Yayyyyy, you win!!");
}
function guess(btn) {
console.log("user guessed: " + btn);
if (!gamePlaying) {
return;
}
if (pattern[guessCounter] == btn) {
if (guessCounter == progress) {
if (progress == pattern.length - 1) {
winGame();
} else {
// document.getElementById("timeDiv").classList.add("hidden"); // might be useful for styling timer
clearInterval(countDownTimer); // we guess correctly so stop timer
progress++;
playClueSequence();
}
} else {
guessCounter++;
}
//guessCounter++;
} else {
loseGame();
}
}
// Sound Synthesis Functions
const freqMap = {
1: 261.6,
2: 329.6,
3: 392,
4: 466.2,
5: 432.8,
6: 336.2
};
function playTone(btn, len) {
o.frequency.value = freqMap[btn];
g.gain.setTargetAtTime(volume, context.currentTime + 0.05, 0.025);
tonePlaying = true;
setTimeout(function() {
stopTone();
}, len);
}
function startTone(btn) {
if (!tonePlaying) {
o.frequency.value = freqMap[btn];
g.gain.setTargetAtTime(volume, context.currentTime + 0.05, 0.025);
tonePlaying = true;
}
}
function stopTone() {
g.gain.setTargetAtTime(0, context.currentTime + 0.05, 0.025);
tonePlaying = false;
}
//Page Initialization
// Init Sound Synthesizer
var context = new AudioContext();
var o = context.createOscillator();
var g = context.createGain();
g.connect(context.destination);
g.gain.setValueAtTime(0, context.currentTime);
o.connect(g);
o.start(0);
body {
font-family: helvetica, arial, sans-serif;
margin: 2em;
background-color: slategrey;
color: white;
}
h1 {
font-family: verdana, arial, sans-serif;
color: yellow;
}
button {
padding: 15px;
border-radius: 15px;
}
#gameButtonArea > button {
width: 200px;
height: 200px;
margin: 2px;
}
.hidden {
display: none;
}
#button1 {
background: lightgreen;
}
#button1:active,
#button1.lit {
background: green;
}
#button2 {
background: lightblue;
}
#button2:active,
#button2.lit {
background: blue;
}
#button3 {
background: pink;
}
#button3:active,
#button3.lit {
background: red;
}
#button4 {
background: lightyellow;
}
#button4:active,
#button4.lit {
background: yellow;
}
#button5 {
background: lightgray;
}
#button5:active,
#button5.lit {
background: black;
}
#button6 {
background: white;
}
#button6:active,
#button6.lit {
background: purple;
}
#timeDiv {
position: relative;
font-weight: bold;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Hello!</title>
<!-- import the webpage's stylesheet -->
<link rel="stylesheet" href="/style.css" />
<!-- import the webpage's javascript file -->
<script src="/script.js" defer></script>
</head>
<body>
<h1>Memory Game</h1>
<div id="timeDiv" class="hidden">Time remaing: 0</div>
<p>
Welcome to the game that will test your memory!
</p>
<button id="startBtn" onclick="startGame()">
Start
</button>
<button id="stopBtn" class="hidden" onclick="stopGame()">
Stop
</button>
<div id="gameButtonArea">
<button
id="button1"
onclick="guess(1)"
onmousedown="startTone(1)"
onmouseup="stopTone()"
></button>
<button
id="button2"
onclick="guess(2)"
onmousedown="startTone(2)"
onmouseup="stopTone()"
></button>
<button
id="button3"
onclick="guess(3)"
onmousedown="startTone(3)"
onmouseup="stopTone()"
></button>
<button
id="button4"
onclick="guess(4)"
onmousedown="startTone(4)"
onmouseup="stopTone()"
></button>
<button
id="button5"
onclick="guess(5)"
onmousedown="startTone(5)"
onmouseup="stopTone()"
></button>
<button
id="button6"
onclick="guess(6)"
onmousedown="startTone(6)"
onmouseup="stopTone()"
></button>
</div>
</body>
</html>

CSS Animation Won't Trigger a Second Time

I'm trying to make a little game. Kinda stupid, but I want there to be this random event that pops up and does a little CSS Keyframe animation. The end goal is to get it to pop up when the random event triggers, and then go away when the animation is over. When running the code, I can get it to work the first time, but the second time the animation doesn't trigger and only the text shows up. Any ideas?
var myFood = document.getElementById("myFood");
var myWood = document.getElementById("myWood");
var myGold = document.getElementById("myGold");
var myButton = document.getElementById("myButton");
var output = document.getElementById("output");
var randomFoodEvent = document.getElementById("event");
var foodCount = 0;
var woodCount = 0;
var goldCount = 0;
myButton.addEventListener("click", buttonClick, false);
window.addEventListener("keydown", keydownHandler, false);
function keydownHandler(event) {
console.log("keyCode = " + event.keyCode);
if (event.keyCode === 13) {
buttonClick();
} else if (event.keyCode === 70) {
foodCount++;
myFood.innerHTML = "<strong>F</strong>ood: " + foodCount;
var randomFoodNum = Math.floor(Math.random() * 100) + 1;
if (randomFoodNum === 50) {
randomFoodEvent.className = "playEvent";
randomFoodEvent.innerHTML = "Some villagers stole your food!";
foodCount = foodCount - 25;
}
} else if (event.keyCode === 87) {
woodCount++;
myWood.innerHTML = "<strong>W</strong>ood: " + woodCount;
} else if (event.keyCode === 71) {
goldCount++;
myGold.innerHTML = "<strong>G</strong>old: " + goldCount;
}
}
randomFoodEvent.addEventListener("animationend", function() {
randomFoodEvent.classList.remove = "playEvent";
randomFoodEvent.innerHTML = "";
});
function buttonClick() {
console.log("Button Clicked!");
if ((foodCount >= 100) && (woodCount >= 100) && (goldCount >= 100)) {
output.textContent = "You win!";
}
}
/* The animation code */
#keyframes example {
from {
background-color: red;
}
to {
background-color: yellow;
}
}
/* The element to apply the animation to */
.playEvent {
animation-name: example;
animation-duration: 4s;
}
<h1>Buttons and Keyboard Events</h1>
<p id="output">
Get 100 Food, 100 Wood, and 100 Gold to Win the Game!
</p>
<p id="myFood"><strong>F</strong>ood: 0</p>
<p id="myWood"><strong>W</strong>ood: 0</p>
<p id="myGold"><strong>G</strong>old: 0</p>
<p id="event">
</p>
<button id="myButton">Click Me to Win</button>
Sorry that there's a lot of code, I couldn't think of a better way to show what I'm trying to do without showing the whole thing.
Thanks!
EDIT: Heres a JSFiddle
Syntax error randomFoodEvent.classList.remove("playEvent");
var myFood = document.getElementById("myFood");
var myWood = document.getElementById("myWood");
var myGold = document.getElementById("myGold");
var myButton = document.getElementById("myButton");
var output = document.getElementById("output");
var randomFoodEvent = document.getElementById("event");
var foodCount = 0;
var woodCount = 0;
var goldCount = 0;
myButton.addEventListener("click", buttonClick, false);
window.addEventListener("keydown", keydownHandler, false);
function keydownHandler(event) {
console.log("keyCode = " + event.keyCode);
if (event.keyCode === 13) {
buttonClick();
} else if (event.keyCode === 70) {
foodCount++;
myFood.innerHTML = "<strong>F</strong>ood: " + foodCount;
var randomFoodNum = Math.floor(Math.random() * 100) + 1;
if (randomFoodNum === 50) {
randomFoodEvent.className = "playEvent";
randomFoodEvent.innerHTML = "Some villagers stole your food!";
foodCount = foodCount - 25;
}
} else if (event.keyCode === 87) {
woodCount++;
myWood.innerHTML = "<strong>W</strong>ood: " + woodCount;
} else if (event.keyCode === 71) {
goldCount++;
myGold.innerHTML = "<strong>G</strong>old: " + goldCount;
}
}
randomFoodEvent.addEventListener("animationend", function() {
randomFoodEvent.classList.remove("playEvent");
randomFoodEvent.innerHTML = "";
});
function buttonClick() {
console.log("Button Clicked!");
if ((foodCount >= 100) && (woodCount >= 100) && (goldCount >= 100)) {
output.textContent = "You win!";
}
}
/* The animation code */
#keyframes example {
from {
background-color: red;
}
to {
background-color: yellow;
}
}
/* The element to apply the animation to */
.playEvent {
animation: example 4s 1;
}
<!doctype.html>
<html>
<head>
<title>
Keyboards and Buttons
</title>
</head>
<body>
<h1>Buttons and Keyboard Events</h1>
<p id="output">
Get 100 Food, 100 Wood, and 100 Gold to Win the Game!
</p>
<p id="myFood"><strong>F</strong>ood: 0</p>
<p id="myWood"><strong>W</strong>ood: 0</p>
<p id="myGold"><strong>G</strong>old: 0</p>
<p id="event">
</p>
<button id="myButton">Click Me to Win</button>
</body>
</html>

Auto-Play feature not executing in JS

I have somewhat of a baseball game, obviously there are not bases or hits. Its all stikes, balls and outs. The buttons work and the functionality of the inning (top and bottom as well as count) are working. I want this to ideally randomly throw a pitch on its own every few seconds. Basically to randomly "click" the ball or strike button. I am trying to use the setTimeout function with no success. Any help?
HTML:
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" type="text/css" href="bullpen.css">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Bullpen</title>
</head>
</html>
<body>
<button id=buttons onclick="playBall()">Auto-Play</button>
<h2>Inning: <span id=inningHalf></span> <span id=inningNum></span></h2>
<div id=buttons>
<button onclick="throwBall(), newInning()">Ball</button>
<button onclick="throwStrike(), newInning()">Strike</button>
</div>
<h2>Count: <span id=ball>0</span> - <span id=strike>0</span></h2>
<h2>Outs: <span id=out>0</span></h2>
<h2>----------------</h2>
<h2>Walks: <span id=walks>0</span></h2>
<h2>Strikeouts: <span id=strikeout>0</span></h2>
<script src="bullpen.js"></script>
</body>
</html>
JS:
var ball = 0;
var strike = 0;
var out = 0;
var walks = 0;
var strikeout = 0;
//---------------------------------
var outPerInning = 0;
var inning = 1;
//---------------------------------
document.getElementById('inningNum').innerHTML = inning;
document.getElementById('inningHalf').innerHTML = '▲';
function throwBall(){
ball++;
document.getElementById('ball').innerHTML = ball;
if (ball == 4){
ball = 0;
strike = 0;
walks++;
document.getElementById('walks').innerHTML = walks;
document.getElementById('strike').innerHTML = 0;
document.getElementById('ball').innerHTML = 0;
}
};
function throwStrike(){
strike++;
document.getElementById('strike').innerHTML = strike;
if(strike == 3){
ball = 0;
strike = 0;
strikeout++;
out++;
outPerInning++;
document.getElementById('strikeout').innerHTML = strikeout;
document.getElementById('out').innerHTML = out;
document.getElementById('strike').innerHTML = 0;
document.getElementById('ball').innerHTML = 0;
}
};
function newInning(){
if(out == 3){
ball=0;
strike=0;
out=0;
document.getElementById('strike').innerHTML = 0;
document.getElementById('ball').innerHTML = 0;
document.getElementById('out').innerHTML = 0;
}
if(outPerInning == 3){
document.getElementById('inningHalf').innerHTML = '▼';
}
if(outPerInning == 6){
inning++;
document.getElementById('inningHalf').innerHTML = '▲';
outPerInning = 0;
document.getElementById('inningNum').innerHTML = inning;
}
};
function playBall(){
var play = Math.random;
if(play >= 0.4){
throwStrike();
newInning();
}
else{
throwBall();
newInning();
}
setTimeout(playBall, 5000);
};
CSS if needed:
h2{
margin-left: 50px;
font-size: 50px;
}
button{
font-size: 45px;
}
#buttons{
width: 227px;
margin-left:50px;
margin-top: 20px;
}
Perhaps this is the problem:
function playBall(){
var play = math.random;
if(play >= 0.4){
throwStrike;
newInning();
}
else{
throwBall;
newInning();
}
setTimeout(playBall, 5000);
};
Should be
function playBall(){
var play = Math.random();
if(play >= 0.4){
throwStrike(); //call the function
newInning();
}
else{
throwBall(); //call the function
newInning();
}
setTimeout(playBall, 5000);
};
You were not calling these functions!
Here is a working fiddle: https://jsfiddle.net/av6vsp7g/

JS: Slideshow inaccurate result

Hi I write this simple javascript slideshow cause I want to write my own slideshow in javascript. It automatically change the images by a set time interval. But when I try to click the backward and forward function the result is not accurate or the images are in order.
var images = ["http://i1214.photobucket.com/albums/cc487/myelstery/1.jpg","http://i1214.photobucket.com/albums/cc487/myelstery/2.jpg","http://i1214.photobucket.com/albums/cc487/myelstery/3.jpg"];
var i = 0;
var count = images.length;
function slidingImages()
{
i = i % count;
document.banner.src = images[i];
i++;
}
function forward()
{
i = (i + 1) % count;
document.banner.src=images[i];
}
function backward()
{
if (i <= 0)
{
i = count - 1;
}
else
{
i--;
}
document.banner.src=images[i];
}
window.onload = function()
{
slidingImages(),setInterval(slidingImages, 3000)
};
<center>
<p>
<img src="images/1.jpg" name="banner" id="name"/>
</p>
<input type="button" value="«prev" onClick="backward()">
<input type="button" value="next»" onClick="forward()">
</center>
What is the solution so my slideshow would be accurate?
This will pause the automatic behavior when the mouse is within the red rectangle and continue in auto mode once the mouse is out of the red rectangle. The buttons of course work as expected.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
fieldset { width: -moz-fit-content; width: -webkit-fit-content; width: fit-content; border: 1px solid red; }
</style>
</head>
<body>
<section>
<p>
<img src="images/1.jpg" name="banner" id="name"/>
</p>
<fieldset id="control">
<input id="prev" type="button" value="◄">
<input id="next" type="button" value="►">
</fieldset>
</section>
<script>
var images = ["http://i1214.photobucket.com/albums/cc487/myelstery/1.jpg","http://i1214.photobucket.com/albums/cc487/myelstery/2.jpg","http://i1214.photobucket.com/albums/cc487/myelstery/3.jpg"];
var i = -1;
var count = images.length;
var prev = document.getElementById('prev');
var next = document.getElementById('next');
var control = document.getElementById('control');
var autoSlide;
window.onload = auto;
function auto() {
autoSlide = setInterval(fwd, 3000) };
function pause() {
clearInterval(autoSlide);
}
function fwd() {
if (i >= 0 && i < 2)
{
i += 1;
}
else
{
i = 0;
}
document.banner.src=images[i];
}
function rev() {
if (i > 0 && i <= 2)
{
i -= 1;
}
else
{
i = 2;
}
document.banner.src=images[i];
}
prev.addEventListener('click', function() {
rev();
}, false);
next.addEventListener('click', function() {
fwd();
}, false);
control.addEventListener('mouseover', function() {
pause();
}, false);
control.addEventListener('mouseout', function() {
auto();
}, false);
</script>
</body>
</html>

User Controls not working for image loop

i have tried it within the loop function but it says the function isn't being used so i put it outside still doesnt work and i dont know how to fix it as i thought that would work, rmember first day on javascript, thanks for the help in advance and please no jquery.
<html>
<head>
<style type="text/css">
#PictureContainer {
height: 300px;
width: 500px;
margin: 0 auto;
overflow: hidden;
display: inline-block;
}
#SliderWrapper {
width: 628px;
height: 300px;
margin: 0 auto;
overflow: hidden;
}
#image {
height: 300px;
width: 500px;
}
#Next {
float: right;
}
#Before {
float: left;
}
</style>
</head>
<body>
<div id="SliderWrapper">
<img id="Next" src="Forward.png" alt="Forward">
<img id="Before" src="Back.png" alt="Back">
<div id="PictureContainer">
<img id="image" src="html.png" alt="HTML">
</div>
</div>
<script language="javascript" type="text/javascript">
var i = 1;
function loop() {
i = i+1;
if(i == 5){
i = 1;
}
if (i == 1) {
document.getElementById('image').src = "html.png";
} else if(i == 2) {
document.getElementById('image').src = "css3.png";
} else if (i == 3) {
document.getElementById('image').src = "WebdevLogo's.jpg";
} else {
document.getElementById('image').src = "WebdevLogo's.jpg";
}
}
var pictureloop = setInterval(loop, 3000);
function Forward() {
if(i == 5) {
i = 1;
} else {
i = i+1;
}
}
function Back() {
if(i == 1) {
i = 4;
} else {
i = -1;
}
}
</script>
</body>
</html>
You have a function called loop, but you never call it, so it's never changing the source attribute of the image. In the forward and back functions, add a call to the loop function at the end. There are also a few problems internally with Back() that I've fixed.
function Forward() {
if(i == 5) {
i = 1;
} else {
i++;
}
loop();
}
function Back() {
if(i == 1) {
i = 5;
} else {
i--;
}
loop();
}
Within the loop() function, consider using a switch block instead of all those else ifs. Also in the loop function, use the increment operator - i++; - which increases the value by 1, rather than the manual statement i = i+1; Also, the if i==5 statement is redundant. You already have it in your Forward function.
this is more of a question for https://codereview.stackexchange.com/ but here are a few things that would make this code cleaner.
instead of duplicating image setting code, declare an array of images.
var images = ['img1.png','img2.png'];
var currentImage = 0;
function forward() {
currentImage++;
if (currentImage > images.length-1) currentImage == 0;
setImage()
}
function setImage() {
document.getElementById('image').src = images[currentImage];
}
setInterval(forward, 5000);

Categories

Resources