Need help fixing a bug in a browser game - javascript

This is a very simple browser memory game which you need to to flip all the matched cards in order to win.
The bug :
In the game if you click fast enough you can flip more than 2 cards.
I've tried a lot to fix it but couldn't figure it out by myself. I would appreciate any help in solving this issue as I am new to JavaScript and it's still hard for me fix those basic bugs.
Game files:
HTML:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>My App</title>
<link rel="stylesheet" href="css/game.css" />
</head>
<body>
<button class="Change User" onclick="change(this)">Change User</button>
<div class="header">
<img src="img/layout/logo.png">
<h1>Memory Monsters</h1>
<p id="Play Again"></p>
</div>
<div class="card" data-card="1" onclick="cardClicked(this)">
<img src="img/cards/1.png">
<img class="back" src="img/cards/back.png">
</div>
<div class="card" data-card="7" onclick="cardClicked(this)">
<img src="img/cards/7.png">
<img class="back" src="img/cards/back.png">
</div>
<div class="card" data-card="1" onclick="cardClicked(this)">
<img src="img/cards/1.png">
<img class="back" src="img/cards/back.png">
</div>
<div class="card" data-card="7" onclick="cardClicked(this)">
<img src="img/cards/7.png">
<img class="back" src="img/cards/back.png">
</div>
<div class="card" data-card="5" onclick="cardClicked(this)">
<img src="img/cards/5.png">
<img class="back" src="img/cards/back.png">
</div>
<div class="card" data-card="5" onclick="cardClicked(this)">
<img src="img/cards/5.png">
<img class="back" src="img/cards/back.png">
</div>
<script src="js/game.js"></script>
</body>
</html>
javascript:
var getElementsByClassName = prompt ('What is your name?');
window.localStorage.setItem ('name', 'dan');
function change(username) {
prompt('What is your name?');
}
// Those are global variables, they stay alive and reflect the state of the game
var elPreviousCard = null;
var flippedCouplesCount = 0;
// This is a constant that we dont change during the game (we mark those with CAPITAL letters)
var TOTAL_COUPLES_COUNT = 3;
// Load an audio file
var audioWin = new Audio('sound/win.mp3');
// This function is called whenever the user click a card
function cardClicked(elCard) {
// If the user clicked an already flipped card - do nothing and return from the function
if (elCard.classList.contains('flipped')) {
return;
}
// Flip it
elCard.classList.add('flipped');
// This is a first card, only keep it in the global variable
if (elPreviousCard === null) {
elPreviousCard = elCard;
} else {
// get the data-card attribute's value from both cards
var card1 = elPreviousCard.getAttribute('data-card');
var card2 = elCard.getAttribute('data-card');
// No match, schedule to flip them back in 1 second
if (card1 !== card2){
setTimeout(function () {
elCard.classList.remove('flipped');
elPreviousCard.classList.remove('flipped');
elPreviousCard = null;
}, 1000)
} else {
// Yes! a match!
flippedCouplesCount++;
elPreviousCard = null;
// All cards flipped!
if (TOTAL_COUPLES_COUNT === flippedCouplesCount) {
audioWin.play();
// and finally add a button to call resetCard()
document.getElementById("Play Again").innerHTML =
'<button onclick="resetCard();">Play Again</button>';
}
}
}
}
function resetCard() {// to erase the flipped classes
var cardclass = document.getElementsByClassName("card");
for (i = 0; i < cardclass.length; i++) {
cardclass[i].classList.remove("flipped");
document.getElementById("Play Again").innerHTML = "";
}
}
CSS:
.header {
background-color: lightblue;
padding: 20px;
border-bottom: 10px solid darkcyan;
color:darkcyan;
font-size: 1.5em;
text-align: center;
}
.header img {
float:right;
}
.card {
background-color: pink;
height: 165px;
width: 165px;
float: left;
margin: 5px;
}
.card img {
position: absolute;
}
.flipped .back {
display: none;
}

i made a game like this. you need to create a variable that starts on 0
let tries = 0;
then add one to it each time a card is selected. make sure to not allow it to count if a card that is already flipped is clicked again. here is some of the code from the function that is run on my onclick. I am using a React framework, but if you write this logic in your JS function, it is what you will need to make it work
selected = (event) => {
if (canClick === true) {
let id = event.currentTarget.id; //card0
let idString = id.toString(); //"card0"
//ONLY ALLOW A CARD TO BE CLICKED IF ITS FACE DOWN
if (this.state[idString] === cardBack) {
idString = idString.replace(/card/g, ''); //"0"
this.setState({[id] : arrayRandom[idString]});
//FIRST PICK
if (counter % 2 == 1) {
curCard1 = arrayRandom[idString].toString();
id1 = id;
counter++;
//SECOND PICK
} else {
//MAKE SURE A CARD DOESN'T GET SELECTED TWICE IN A ROW AND STAY FACE UP
if (id === id1) {
console.log("Select a different card for your second pick");
} else {
counter++;
tries++;
canClick = false; //STOP USER FROM SELECTING ANOTHER CARD
curCard2 = arrayRandom[idString].toString();
id2 = id;
setTimeout(() => {canClick = true}, 1000); //USER CAN PICK AGAIN IN 1 SEONCD
//IF THERE'S A MATCH - CARDS STAY FLIPPED, SCORE INCREASES BY 1
if (curCard1 == curCard2) {
score = score + 1;
//IF THERE'S NO MATCH - CARDS FLIP FACE DOWN AFTER A SECOND
} else {
setTimeout(() => {
this.setState({[id1]: cardBack});
this.setState({[id2]: cardBack});
}, 1000);
}
}
}
} else {
console.log("This card has already been flipped, select another one");
}
}
}
here is my game
https://reactcardmatch.netlify.com/

Related

How do I make a function that reset the game on click

I am working on a rock paper scissor game. I'm very new to javascript and only know the basics. The code is a little sloppy. What I want is to be able to continue playing the game after a choice is selected. For example, right now if I click rock, the CPU will randomize a result, but then if I click on paper, the result will stay on the screen and the new result will overlap the old one.
I was thinking of adding another condition to the if statements. Also, I was thinking of adding another function to the return of the if statement that might reset it.
html
<div class="main-container">
<div class="score">
<p>You:0</p>
<p>Computer:0</p>
</div>
<div class="user-choice">
<img id="rock" class="choice" src="icons/rock.png">
<img id="paper" class="choice" src="icons/paper.png">
<img id="scissors" class="choice" src="icons/scissors.png">
</div>
<div class="cpu-result">
<img class="cpu-rock" src="icons/rock.png">
<img class="cpu-paper" src="icons/paper.png">
<img class="cpu-scissors" src="icons/scissors.png">
</div>
</div>
js
const userChoice = document.querySelectorAll('.choice')
const cpuScissors = document.querySelector('.cpu-scissors')
const cpuPaper = document.querySelector('.cpu-paper')
const cpuRock = document.querySelector('.cpu-rock')
function cpuChoice() {
const rand = Math.random()
if (rand < .34) {
cpuPaper.style.display = 'inline-block'
} else if (rand >= .67) {
cpuRock.style.display = 'inline-block'
} else {
cpuScissors.style.display = 'inline-block'
}
}
userChoice.forEach(userChoice =>
userChoice.addEventListener('click', cpuChoice))
css
.cpu-scissors {
display: none;
}
.cpu-paper {
display: none;
}
.cpu-rock {
display: none;
}
.cpu-result img {
position: absolute;
height: 11rem;
}
Firstly, you need to remove position: absolute; for img which was causing the overlapping.
Secondly, each time you call cpuChoice(), you need to hide the previous element before showing the current element.
const userChoice = document.querySelectorAll('.choice')
const cpuScissors = document.querySelector('.cpu-scissors')
const cpuPaper = document.querySelector('.cpu-paper')
const cpuRock = document.querySelector('.cpu-rock')
let currentItem;
function cpuChoice() {
const rand = Math.random();
if (currentItem) {
currentItem.style.display = 'none';
}
if (rand < .34) {
cpuPaper.style.display = 'inline-block';
currentItem = cpuPaper;
} else if (rand >= .67) {
cpuRock.style.display = 'inline-block';
currentItem = cpuRock;
} else {
cpuScissors.style.display = 'inline-block';
currentItem = cpuScissors;
}
}
userChoice.forEach(userChoice =>
userChoice.addEventListener('click', cpuChoice));
.cpu-scissors {
display: none;
}
.cpu-paper {
display: none;
}
.cpu-rock {
display: none;
}
.cpu-result img {
height: 5rem;
}
<div class="main-container">
<div class="score">
<p>You:0</p>
<p>Computer:0</p>
</div>
<div class="user-choice">
<img id="rock" class="choice" src="icons/rock.png">
<img id="paper" class="choice" src="icons/paper.png">
<img id="scissors" class="choice" src="icons/scissors.png">
</div>
<div class="cpu-result">
<img class="cpu-rock" src="icons/rock.png">
<img class="cpu-paper" src="icons/paper.png">
<img class="cpu-scissors" src="icons/scissors.png">
</div>
</div>
You don't need all those IDs and Classes.
Use Indexes!
Using indexes you can also retrieve the winner
See this answer: https://stackoverflow.com/a/53983473/383904
const moves = ["Rock", "Paper", "Scissors"],
messages = ["You won!", "AI won", "It's a draw!"], // [PL, AI, draw]
score = [0, 0, 0], // [PL, AI, draw]
ELS = sel => document.querySelectorAll(sel),
EL_result = ELS("#result")[0],
EL_PLScore = ELS("#PLScore")[0],
EL_AIScore = ELS("#AIScore")[0],
ELS_ai = ELS(".ai");
function game() {
const PL = +this.dataset.user; // Get played index as integer
const AI = ~~(Math.random() * 3); // All you need: 0, 1, 2
const result = PL === AI ? 2 : (AI + 1) % 3 === PL ? 0 : 1; // 0=PLwins 1=AIwins 2=draw
score[result]++; // Increment PL or AI's score (Increments number of draws too ;) )
EL_result.innerHTML = `You: ${moves[PL]}, AI: ${moves[AI]}, ${messages[result]}`;
EL_PLScore.textContent = score[0];
EL_AIScore.textContent = score[1];
ELS_ai.forEach(el => el.classList.remove('inline-block')); // Hide all
ELS_ai[AI].classList.add('inline-block'); // Show one
}
// EVENTS:
document.querySelectorAll("[data-user]").forEach(el => el.addEventListener("click", game));
.ai {
display: none;
}
.ai.inline-block {
display: inline-block
}
<div class="main-container">
<div class="score">
<span>You: <span id="PLScore">0</span></span>
<span>Computer: <span id="AIScore">0</span></span>
</div>
<div class="user-choice">
<img data-user="0" src="//placehold.it/50x50/888?text=ROCK">
<img data-user="1" src="//placehold.it/50x50/eee?text=PAPER">
<img data-user="2" src="//placehold.it/50x50/0bf?text=SCISSORS">
</div>
<div class="cpu-result">
<img class="ai" src="//placehold.it/50x50/888?text=ROCK">
<img class="ai" src="//placehold.it/50x50/eee?text=PAPER">
<img class="ai" src="//placehold.it/50x50/0bf?text=SCISSORS">
</div>
<div id="result"></div>
</div>

Building a Wheel of Fortune game and I'm trying to get the keypress event to detect a letter in the random word array

I'm working on a Wheel of Fortune game where a random word is chosen from an array. I created a function below my game function to detect the key pressed from a list of letters displayed on screen from A-Z. My problem is that I can't get the game to detect the key pressed until the randomWord() function is fired after the playGame() button is pressed. I'm trying to get the letter pressed by the user in the buttonPress() function to match a letter in the wordChoice.length loop and display on the screen where the _ would be and then rule out the letter after it's been used. I tried creating the letterClicked variable and making it global so that my playGame() function can access it but I'm not having any luck matching the letter selected by the user and the letter in the display box above the play button. What am I doing wrong here? I tried console logging throughout the randomWord() function but the keypress is only being detected after you click play and essentially reset the game. Here is my code below. Thanks for your help!
<DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Wheel of Fortune</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="main.css">
</head>
<body>
<body>
<div id="container">
<div id="header">
<p class="welcome">Welcome to Wheel of Fortune!</p>
<!-- The letters will be tied to the number of letters in the random array -->
<p class="letters">There are <span id="numbers">0</span> letters in this word</p>
<!-- The user will be given a number of choices and with each wrong choice, they lose a turn -->
<p class="lives">You have <span id="guesses">0</span> guesses left</p>
<span id="words"></span><br>
<button id="play" onclick="playGame()">Play</button>
</div>
<div id="alphabet" onclick="buttonPress(event)">
<button>A</button>
<button>B</button>
<button>C</button>
<button>D</button>
<button>E</button>
<button>F</button>
<button>G</button>
<button>H</button>
<button>I</button>
<button>J</button>
<button>K</button>
<button>L</button>
<button>M</button>
<br>
<button>N</button>
<button>O</button>
<button>P</button>
<button>Q</button>
<button>R</button>
<button>S</button>
<button>T</button>
<button>U</button>
<button>V</button>
<button>W</button>
<button>X</button>
<button>Y</button>
<button>Z</button>
</div>
<span id="your-guess">You guessed </span>
</div>
<script src="main.js"></script>
</body>
</html>
body {
margin: 0 auto;
width: 1000px;
font-size: 20px;
background: url("http://res.cloudinary.com/angelrodriguez/image/upload/c_crop,h_624/v1534810805/wheeloffortune.jpg");
background-size: cover;
color: white;
}
#header {
margin: 20px;
}
#alphabet {
margin: 20px;
}
button {
border: 2px solid blue;
font-size: 20px;
}
#words {
font-size: 30px;
margin: 10px;
letter-spacing: 20px;
}
#play {
margin: 20px;
}
// 3. Quit the game if the player wants to.
// 5. Keep track of letters the player has guessed.
// 6. Show the player their progress.
// 7. Finish when the player has guessed the word.
// Create global variables
let gameOver = false;
var guessesLeft = 6;
var letterClicked;
var wordArray = ["JAVASCRIPT", "ARRAYS", "FUNCTIONS", "HOISTING", "RECURSION", "EVENTS", "KEYUP", "TERNARY"];
// 1. Pick a random word.
//Start a new game
function playGame() {
newGame.addEventListener("click", function() {
//fire the randomWord function to generate a new word
randomWord();
})
}
// Pass the letter event from buttonPress into the randomWord function
function randomWord(letter) {
var answerList = [];
// console.log(answerList);
// letterGuessed = "";
console.log(letterClicked);
var wordChoice = wordArray[Math.floor(Math.random() * wordArray.length)];tbw
var wordSplit = wordChoice.split('');
// console.log(wordSplit);
for (var i = 0; i < wordSplit.length; i++) {
answerList[i] = "_";
}
// if the letter is in the word
// Update the players progress with the guess
for (var z = 0; z < wordChoice.length; z++) {
if (wordChoice[z] === letterClicked) {
letterClicked = answerList[i];
// answerList[i].innerHTML = letterGuessed;
}
}
//Display underscores on page representing each word in the random word
wordDisplay.innerHTML = answerList;
//Display number of letters in the random word on the page
var remainingLetters = wordChoice.length;
letterCount.innerHTML = "The word is " + remainingLetters +
" letters long";
}
// 2. Take the player’s guess.
function buttonPress(e) {
letterClicked = e.target.textContent;
document.getElementById("your-guess").innerHTML = "You guessed the letter " + letterClicked;
//fix issue with clicking divs
}
// If the player wants to quite the game {
// Quit the game
// }
// Grab elements
var numbers = document.querySelector("#numbers");
var guesses = document.querySelector("#guesses");
var wordDisplay = document.querySelector("#words");
var letterCount = document.querySelector(".letters");
var newGame = document.querySelector("#play");
var letterBoxes = document.querySelector("#alphabet");
To get a letter in buttonPress you are able to use e.toElement.textContent.
I did some solution, but it's not a great example, i think.
let words = [ "TERNARY"], guessesLeft, chosenWord;
let getRandomWord = words => {
return words[Math.floor(Math.random()*words.length)];
}, updateGuesses = count => {
guesses.innerText = count;
guessesLeft = count;
}, updateWords = word => {
document.getElementById('words').innerHTML = word;
}, hideAlphabet = () => alphabet.style.display = 'none',
setGameStatus = status => document.getElementById("status").innerHTML = status;
play.addEventListener('click', e => {
e.target.style.display = 'none'; // hide when game started.
alphabet.style.display = 'block';
chosenWord = getRandomWord(words);
updateGuesses(chosenWord.length);
updateWords(String("*").repeat(chosenWord.length))
});
alphabet.addEventListener('click', e => {
let letter = e.toElement.textContent;
e.toElement.disabled = true;
if (!new RegExp(letter).test(chosenWord)) {
updateGuesses(guessesLeft -1);
} else {
let newString = document.getElementById('words').innerHTML.split(''), indexesOfALetter = [];
for(let i = 0; i < chosenWord.length; i += 1) // here for is a fastest way.
if (chosenWord[i] === letter) indexesOfALetter.push(i);
indexesOfALetter.forEach(i => newString[i] = letter);
updateWords(newString.join(''));
}
if (!/\*/.test(document.getElementById('words').innerHTML)) {
hideAlphabet();
setGameStatus("Congratulations! You won that game");
}
if (guessesLeft < 1) {
hideAlphabet();
setGameStatus("Unfortunately, you lost the game ;(");
updateWords(chosenWord);
}
});
body {
margin: 0 auto;
width: 1000px;
font-size: 20px;
color: black;
}
#header {
margin: 20px;
}
#alphabet {
display: none;
margin: 20px;
}
button {
border: 2px solid blue;
font-size: 20px;
}
#words {
font-size: 30px;
margin: 10px;
letter-spacing: 20px;
}
#play {
margin: 20px;
}
<div id="container">
<div id="header">
<p class="welcome">Welcome to Wheel of Fortune!</p>
<!-- The user will be given a number of choices and with each wrong choice, they lose a turn -->
<p class="lives">You have <span id="guesses">0</span> guesses left</p>
<span id="words"></span><br>
<button id="play">Play</button>
</div>
<div id="alphabet">
<button>A</button>
<button>B</button>
<button>C</button>
<button>D</button>
<button>E</button>
<button>F</button>
<button>G</button>
<button>H</button>
<button>I</button>
<button>J</button>
<button>K</button>
<button>L</button>
<button>M</button>
<br>
<button>N</button>
<button>O</button>
<button>P</button>
<button>Q</button>
<button>R</button>
<button>S</button>
<button>T</button>
<button>U</button>
<button>V</button>
<button>W</button>
<button>X</button>
<button>Y</button>
<button>Z</button>
</div>
<span id="status"></span>
</div>

TicTacToe - trouble alternating players

First mouse click gives me the expected 'x' marker but the next mouse click results in the alert ("Player o: tile has already been selected) even though the grid-item is blank. What am I doing wrong?
In the HTML body, I have created a 3x3 grid, 9 gridItems in total.
$(document).ready(function(){
let grid = $("#grid-container")
let gridItem = $(".grid-item")
function select(){
for (i = 0; i < gridItem.length; i++){
gridItem[i].addEventListener("click", function(){
if ($(this).html() == ""){
$(this).html("x");
nextSelect();
} else {alert ("Player X: tile has already been selected"); select()}
})
}
}
function nextSelect(){
for (i = 0; i < gridItem.length; i++){
gridItem[i].addEventListener("click", function(){
if ($(this).html() == ""){
$(this).html("o");
select();
} else {alert ("Player o: tile has already been selected"); nextSelect()}
})
}
}
select()
});
The addEventListener should be executed only once. Your problem is that you're adding multiple event handlers. A possible version in the snippet bellow.
The idea is that you only need one function and attach it to click event only once per cell, which is done with jQuery .click(callback). To manage the turns you can use a boolean variable (isTurnOfPlayerOne).
$(document).ready(function() {
let isTurnOfPlayerOne = true;
$(".grid-item").click(handleClick);
function handleClick() {
if ($(this).html() == " ") {
let symbol = (isTurnOfPlayerOne ? "x" : "o");
$(this).html(symbol);
} else {
alert("Tile has already been selected");
}
isTurnOfPlayerOne = !isTurnOfPlayerOne;
}
});
.grid-item {
width: 40px;
height: 40px;
display: inline-block;
border: solid 1px #000;
text-align: center;
margin-bottom: 3px;
line-height: 30px;
font-size: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="grid-container">
<div class="grid-item"> </div>
<div class="grid-item"> </div>
<div class="grid-item"> </div>
<br/>
<div class="grid-item"> </div>
<div class="grid-item"> </div>
<div class="grid-item"> </div>
<br/>
<div class="grid-item"> </div>
<div class="grid-item"> </div>
<div class="grid-item"> </div>
</div>

Return id on next "page" in single page site based on current page id using javascript

I am creating a simple website which should have multiple pages showing a different background and main text, but with the same logo and menu. The next page should slide in from the right when a button is pressed and selecting a page from the menu should transition directly to that page. I have decided to make this a single page site to make use of CSS3 transitions. Example code for the next button (minus transitions) is here: http://jsfiddle.net/xoa029jz/1/
I am currently working out which background and text to display using the following javascript:
function getNextPage(pageid) {
if (pageid == "page-1") {
return $('#page-2');
} else if (pageid == "page-2") {
return $('#page-3');
} else if (pageid == "page-3") {
return $('#page-1');
}
}
The site will have 7 pages, so this seems cumbersome. Is there a better way of using sequential ids in javascript?
The site will only have one image and one sentence per "page", so I don't think it is necessary to use Ajax, but I am willing to be corrected on this.
You can use class in this case which will not bound you for any number of pages,
function getNextPage(pageid) {
if($('.current-page').next('.page-text').length){
return $('.current-page').next('.page-text');
}
return $('.page-text:first');
}
function slideToNext() {
var currentPage = $('.current-page');
var nextPage = getNextPage(currentPage.attr('id'));
$(currentPage).removeClass('current-page');
$(nextPage).addClass('current-page');
var currentBackground = getCurrentBackground();
var nextBackground = getNextBackground(currentBackground);
$('#bg').removeClass(currentBackground);
$('#bg').addClass(nextBackground);
}
function getNextPage(pageid) {
if($('.current-page').next('.page-text').length){
return $('.current-page').next('.page-text');
}
return $('.page-text:first');
}
function getCurrentBackground() {
var bg = $('#bg');
if (bg.hasClass('bg-1')) {
return "bg-1";
} else if (bg.hasClass('bg-2')) {
return "bg-2";
} else if (bg.hasClass('bg-3')) {
return "bg-3";
}
}
function getNextBackground(bg) {
if (bg == "bg-1") {
return "bg-2";
} else if (bg == "bg-2") {
return "bg-3";
} else if (bg == "bg-3") {
return "bg-1";
}
}
.page {
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
background-size: cover;
background-position: center center;
z-index:1;
}
.page-text {
margin-top: 71px;
display: none;
}
.current-page {
display: inline;
visibility: visible;
}
.bg-1 {
background-color:#D8F6CE;
}
.bg-2 {
background-color:#CEECF5;
}
.bg-3 {
background-color:#E2A9F3;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<body class="page bg-1" id="bg">
<div id="page">
<img id="logo" src="images/logo.png" width="295" height="92" />
<div id="menu">
<ul>
<li>
<button>Page 1</button>
</li>
<li>
<button>Page 2</button>
</li>
<li>
<button>Page 3</button>
</li>
</ul>
</div>
<div class="page-text current-page" id="page1">Page 1 text</div>
<div class="page-text" id="page2">Page 2 text</div>
<div class="page-text" id="page3">Page 3 text</div>
<button type="button" onclick="slideToNext()">Next</button>
</div>
</body>
Yes. Get the ID as a number, and increment it:
var num = +pageid[5];
if (num < 7) {
return $('#page-'+(num+1));
}
return $('#page-1');
If there is only 7 pages, cant u loop it, like:
for(var i=0;i<=7;i++){
if (pageid == "page-"+i) {
return $('#page-'+i);
}
}
Change your code to this
//just remove the word page so that only the number will left (e.g. "page"1 )
var nextPage = getNextPage(currentPage.attr('id').replace('page', ''));
Then your function will be shorter and no element count hard coding.
function getNextPage(pageid) {
return $('#page' + (pageid + 1)); //just take care the logic for returning to first page
}

Show images one after one after some interval of time

I am new person in Front End Development and i am facing one major problem is that i have 3 images placed on each others and now i want to move one image so the other image comes up and then it goes and third image comes up after some interval of time.
I want three images on same position in my site but only wants to see these three images one after one after some interval of time.
Please help how i can do this??
May i use marquee property or javascript???
Non-jQuery Option
If you don't want to go down the jquery route, you can try http://www.menucool.com/javascript-image-slider. The setup is just as easy, you just have to make sure that your images are in a div with id of slider and that div has the same dimensions as one of your images.
jQuery Option
The jQuery cycle plugin will help you achieve this. It requires jquery to work but it doesn't need much setting up to create a simple sliple slideshow.
Have a look at the 'super basic' demo:
$(document).ready(function() {
$('.slideshow').cycle({
fx: 'fade' // choose your transition type, ex: fade, scrollUp, shuffle, etc...
});
});
It has many options if you want something a bit fancier.
Here you go PURE JavaScript solution:
EDIT I have added image rotation... Check out live example (link below)
<script>
var current = 0;
var rotator_obj = null;
var images_array = new Array();
images_array[0] = "rotator_1";
images_array[1] = "rotator_2";
images_array[2] = "rotator_3";
var rotate_them = setInterval(function(){rotating()},4000);
function rotating(){
rotator_obj = document.getElementById(images_array[current]);
if(current != 0) {
var rotator_obj_pass = document.getElementById(images_array[current-1]);
rotator_obj_pass.style.left = "-320px";
}
else {
rotator_obj.style.left = "-320px";
}
var slideit = setInterval(function(){change_position(rotator_obj)},30);
current++;
if (current == images_array.length+1) {
var rotator_obj_passed = document.getElementById(images_array[current-2]);
rotator_obj_passed.style.left = "-320px";
current = 0;
rotating();
}
}
function change_position(rotator_obj, type) {
var intleft = parseInt(rotator_obj.style.left);
if (intleft != 0) {
rotator_obj.style.left = intleft + 32 + "px";
}
else if (intleft == 0) {
clearInterval(slideit);
}
}
</script>
<style>
#rotate_outer {
position: absolute;
top: 50%;
left: 50%;
width: 320px;
height: 240px;
margin-top: -120px;
margin-left: -160px;
overflow: hidden;
}
#rotate_outer img {
position: absolute;
top: 0px;
left: 0px;
}
</style>
<html>
<head>
</head>
<body onload="rotating();">
<div id="rotate_outer">
<img src="0.jpg" id="rotator_1" style="left: -320px;" />
<img src="1.jpg" id="rotator_2" style="left: -320px;" />
<img src="2.jpg" id="rotator_3" style="left: -320px;" />
</div>
</body>
</html>
And a working example:
http://simplestudio.rs/yard/rotate/rotate.html
If you aim for good transition and effect, I suggest an image slider called "jqFancyTransitions"
<html>
<head>
<script type="text/javascript">
window.onload = function(){
window.displayImgCount = 0;
function cycleImage(){
if (displayImgCount !== 0) {
document.getElementById("img" + displayImgCount).style.display = "none";
}
displayImgCount = displayImgCount === 3 ? 1 : displayImgCount + 1;
document.getElementById("img" + displayImgCount).style.display = "block";
setTimeout(cycleImage, 1000);
}
cycleImage();
}
</script>
</head>
<body>
<img id="img1" src="./img1.png" style="display: none">
<img id="img2" src="./img2.png" style="display: none">
<img id="img3" src="./img3.png" style="display: none">
</body>
</html>​
Fiddle: http://jsfiddle.net/SReject/F7haV/
arrayImageSource= ["Image1","Image2","Image3"];
setInterval(cycle, 2000);
var count = 0;
function cycle()
{
image.src = arrayImageSource[count]
count = (count === 2) ? 0 : count + 1;
}​
Maybe something like this?

Categories

Resources