Javascript Slideshow with play pause and Next Prev button - javascript

I'm making a slideshow in Javascript with a Play / Pause and Next / Prev. I have manage to slideshow working with play/pause button, but now i wanted to add Next and Prev button to it. Can some one please help me how can i do that.
Here's my HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Simple HTML Slideshow</title>
<style type="text/css">
#slideshow {
margin: 50px auto;
position: relative;
width: 900px;
height: 450px;
padding: 10px;
}
#slideshow > div {
position: absolute;
top: 10px;
left: 10px;
right: 10px;
bottom: 10px;
}
#slideshow > div > img {
width: 100%;
}
#button { text-align: center; }
</style>
<noscript>
Sorry...JavaScript is needed to go ahead.
</noscript>
</head>
<body>
<div id="slideshow">
<div>
<img name="slide" id="imgSlideshow" src="http://themarklee.com/wp-content/uploads/2013/12/snowying.jpg">
</div>
</div>
<div id="button">
Prev
Play/Pause
Next
</div>
</body>
</html>
Here is JavaScript:
<script language="javascript" type="text/javascript">
var i = 0;
var path = new Array();
//var timer = setInterval("slide()",2000);
var timer;
// LIST OF IMAGES
path[0] = "http://themarklee.com/wp-content/uploads/2013/12/snowying.jpg";
path[1] = "http://themarklee.com/wp-content/uploads/2013/12/starlight.jpg";
path[2] = "http://themarklee.com/wp-content/uploads/2013/12/snowstorm.jpg";
path[3] = "http://themarklee.com/wp-content/uploads/2013/12/misty-winter-afternoon.jpg";
function slide() {
document.getElementById("imgSlideshow").src = path[i];
i = (i + 1)%path.length;
//console.log(i);
}
function setTimer(){
if (timer) {
// stop
clearInterval( timer );
timer=null;
}
else {
timer = setInterval("slide()",2000);
}
}
var imgNumber = 1;
var numberOfImg = path.length;
function previousImage() {
if(imgNumber > 1) {
imgNumber--;
}
else {
imgNumber = numberOfImg;
}
document.getElementById("imgSlideshow").src = path[imgNumber-1];
changeCounter(imgNumber, numberOfImg);
}
function nextImage(){
if(imgNumber < numberOfImg){
imgNumber++
}
else{
imgNumber = 1
}
document.getElementById("imgSlideshow").src = path[imgNumber-1];
changeCounter(imgNumber, numberOfImg);
}
function changeCounter(cur, total) {
document.getElementById("counter").innerHTML = cur + "/" + total;
}
document.getElementById("counter").innerHTML = 1 + "/" + path.length;
</script>
Any Help is appreciated and thanks in advance.

Only minor changes in the logic.
var imgNumber = 0;
var path = ["http://themarklee.com/wp-content/uploads/2013/12/snowying.jpg",
"http://themarklee.com/wp-content/uploads/2013/12/starlight.jpg",
"http://themarklee.com/wp-content/uploads/2013/12/snowstorm.jpg",
"http://themarklee.com/wp-content/uploads/2013/12/misty-winter-afternoon.jpg"
];
var numberOfImg = path.length;
var timer = null;
function slide() {
imgNumber = (imgNumber + 1) % path.length;
console.log(imgNumber);
document.getElementById("imgSlideshow").src = path[imgNumber];
changeCounter(imgNumber + 1, numberOfImg);
}
function setTimer() {
if (timer) {
clearInterval(timer);
timer = null;
} else {
timer = setInterval(slide, 2000);
}
return false;
}
function previousImage() {
--imgNumber;
if (imgNumber < 0) {
imgNumber = numberOfImg - 1;
}
document.getElementById("imgSlideshow").src = path[imgNumber];
changeCounter(imgNumber + 1, numberOfImg);
return false;
}
function nextImage() {
++imgNumber;
if (imgNumber > (numberOfImg - 1)) {
imgNumber = 0;
}
document.getElementById("imgSlideshow").src = path[imgNumber];
changeCounter(imgNumber + 1, numberOfImg);
return false;
}
function changeCounter(cur, total) {
document.getElementById("counter").innerHTML = cur + "/" + total;
}
document.getElementById("counter").innerHTML = 1 + "/" + path.length;
#slideshow {
margin: 50px auto;
position: relative;
width: 900px;
height: 450px;
padding: 10px;
}
#slideshow > div {
position: absolute;
top: 10px;
left: 10px;
right: 10px;
bottom: 10px;
}
#slideshow > div > img {
width: 100%;
}
#button {
text-align: center;
}
<div id="slideshow">
<div>
<img name="slide" id="imgSlideshow" src="http://themarklee.com/wp-content/uploads/2013/12/snowying.jpg">
</div>
</div>
<div id="button">
Prev
Play/Pause
Next
</div>
<div id="counter"></div>

Related

Javascript - need an image to disappear momentarily while the the other image transitions

**Hi, fellow Developers! I'm in bit of a rut. I am currently working on making an image fade and transition to another image using Javascript. I'm new to code (and stackoverlow) and am still learning how to program - how can I can make the images fade without being apparent in the background?
What I expected the code to do was fade, transition to the second image, and repeat. It
Here is what the code looks like so far.**
======HTML CODE=====
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Javascript Image Transition</title>
====CSS======
<style>
body {
text-align: center;
}
h1 {
color: green;
}
img {
position: absolute;
left: 400px;
}
</style>
</head>
<body>
<div id="scroll-image">
<img src="SnugBear_home.png" class="test"/>
<img src="img.png" class="test"/>
<img src="img2.png" class="test"/>
</div>
=======Javascript Code=======
<script>
startImageTransition();
function startImageTransition() {
var images = document.getElementsByClassName("test");
for ( var i = 0; i < images.length; ++i) {
images[i].style.opacity = 1;
}
var top = 1;
var cur = images.length - 1;
setInterval(changeImage, 3000);
async function changeImage() {
var nextImage = (1 + cur) % images.length;
images[cur].style.zIndex = top + 1;
images[nextImage].style.zIndex = top;
images[cur].style.zIndex = top;
images[nextImage].style.zIndex = top + 1;
top = top + 1;
images[cur].style.opacity = 1;
cur = nextImage;
}
function transition() {
return new Promise(function(resolve, reject) {
var del = 0.01;
var id = setInterval (changeOpacity, 10);
function changeOpacity() {
images[cur].style.opacity -= del;
if (images[cur].style.opacity <= 0) {
clearInterval(id);
resolve();
}
}
})
}
}
</script>
</body>
</html>
Fading can be made with animation CSS. Liked the code above and I just added a small code `.animate()'.
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Javascript Image Transition</title>
<style>
body {
text-align: center;
}
h1 {
color: green;
}
img {
width: 100px;
height: 100px;
position: absolute;
left: 400px;
}
#one {
background-color: red;
}
#two {
background-color: blue;
}
#three {
background-color: green;
}
</style>
</head>
<body>
<div id="scroll-image">
<img src="SnugBear_home.png" class="test" id="one"/>
<img src="img.png" class="test" id="two"/>
<img src="img2.png" class="test" id="three"/>
</div>
<script>
startImageTransition();
function startImageTransition() {
var images = document.getElementsByClassName("test");
for ( var i = 0; i < images.length; ++i) {
images[i].style.opacity = 1;
}
var top = 1;
var cur = images.length - 1;
setInterval(changeImage, 3000);
async function changeImage() {
var nextImage = (1 + cur) % images.length;
images[cur].style.zIndex = top + 1;
images[cur].animate([
{opacity: 1},
{opacity: 0}
], 3000)
images[nextImage].style.zIndex = top;
images[nextImage].animate([
{opacity: 0},
{opacity: 1}
], 3000)
images[cur].style.zIndex = top;
images[nextImage].style.zIndex = top + 1;
top = top + 1;
images[cur].style.opacity = 1;
cur = nextImage;
}
function transition() {
return new Promise(function(resolve, reject) {
var del = 0.01;
var id = setInterval (changeOpacity, 10);
function changeOpacity() {
images[cur].style.opacity -= del;
if (images[cur].style.opacity <= 0) {
clearInterval(id);
resolve();
}
}
})
}
}
</script>
</body>
</html>

Using setInterval to create a progress bar

I was hoping a kind soul might be able to assist.
I have a slideshow which auto-plays, my intention is to have the next button act as a visual aid, highlighting the when the next frame is coming in.
sync with the autoPlay interval.
Right now, the update func concludes too early, which is the best I have managed to do. Typically I have the clearInterval and setInterval conflicting creating shuddering animations.
What am I doing wrong?
<!doctype html>
<html lang="en">
<head>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
.carousel_wrapper {
height: 50vh;
width: 100%;
position: relative;
}
.carousel_frame {
width: 100%; height: 100%;
}
.carousel_controls {
position: absolute;
bottom: 0;
left: 0;
}
.prev, .next {
height: 50px;
width: 100px;
background: aqua;
display: inline-block;
}
.next {
background: linear-gradient(to right, white 0%, aqua);
}
.carousel_frame:nth-child(1) {
background: red;
}
.carousel_frame:nth-child(2) {
background: blue;
}
.carousel_frame:nth-child(3) {
background: green;
}
</style>
<script>
window.addEventListener('DOMContentLoaded', () => {
const homepage_carousel = new carousel();
});
function carousel() {
const carousel = document.getElementsByClassName('.carousel_wrapper')[0];
const frames = [...document.getElementsByClassName('carousel_frame')];
const prev_button = document.getElementsByClassName('prev')[0];
const next_button = document.getElementsByClassName('next')[0];
this.frameIndex = 1;
prev_button.addEventListener('click', () => {
this.resetPlay();
this.move(-1);
})
next_button.addEventListener('click', () => {
this.resetPlay();
this.move(+1);
})
this.hideAll = () => {
frames.forEach((f) => {
f.style.display = 'none';
});
}
this.show = () => {
this.hideAll();
frames[this.frameIndex - 1].style.display = 'block';
this.update_bg();
}
this.move = (amount) => {
this.frameIndex += amount;
this.frameIndex = (this.frameIndex > frames.length ? 1 : (this.frameIndex < 1) ? frame.lengh : this.frameIndex);
this.show();
}
this.update_bg = () => {
let w = 1;
let test = setInterval(adjust, 10);
function adjust() {
if (w >= 100) {
clearInterval(test);
w = 0;
} else {
w++;
next_button.style.backgroundImage = `linear-gradient(to right, white ${w}%, aqua)`
}
}
setInterval(adjust, 3000);
}
this.autoPlay = () => {
this.move(+1)
this.update_bg();
}
this.resetPlay = () => {
// clearInterval(timer);
// timer = setInterval(this.autoPlay(), 4000);
}
this.show();
const timer = setInterval(this.autoPlay, 3000);
}
</script>
</head>
<body>
<div class='carousel_wrapper'>
<div class='carousel_frame'>
<span>Headline</span>
<span>Description</span>
<span>CTA</span>
</div>
<div class='carousel_frame'>
<span>Headline</span>
<span>Description</span>
<span>CTA</span>
</div>
<div class='carousel_frame'>
<span>Headline</span>
<span>Description</span>
<span>CTA</span>
</div>
<div class='carousel_controls'>
<span class='prev'>Previous</span>
<span class='next'>
Next
</span>
</div>
</div>
</body>
</html>

Why does my <div> element start shaking when I try to move it?

I'm new to Stack Overflow.
I have a simple webpage which tries to move a colored div element back and forth.
However when I run it the div element starts moving correctly but after a few seconds it starts shaking madly, as if its boss refused to give it the salary.
Here is my code:
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Move</title>
<link rel="stylesheet" href="D:\Web\CSS\CSS.css"/>
<script src="D:\Web\JS\JS.js">
</script>
</head>
<body>
<div id="container">
<div id="box">
</div>
</div>
</body>
</html>
JavaScript:
window.onload = function() {
var x = 0;
var box = document.getElementById("box");
setInterval(moveRight, 5);
function moveRight() {
if(x >= 150) {
clearInterval();
setInterval(moveLeft, 5);
} else {
x += 1;
box.style.left = x + "px";
}
}
function moveLeft() {
if(x <= 0) {
clearInterval();
setInterval(moveRight, 5);
} else {
x -= 1;
box.style.left = x + "px";
}
}
}
CSS:
body {
background-color: #246;
}
#container {
width: 200px;
height: 50px;
background: #268;
position: relative;
}
#box {
width: 50px;
height: 50px;
background: #2ac;
position: absolute;
}
Plz help me
Thanks
You're not clearing the interval since you're not passing a variable to it, therefore it's not doing anything. If you set the interval to a variable, you can clear the interval when you switch the direction.
Reference: https://www.w3schools.com/jsref/met_win_clearinterval.asp
Here's an example:
(function() {
var direction;
var x = 0;
var box = document.getElementById("box");
// set the initial direction
direction = setInterval(moveRight, 5);
function moveRight() {
if (x >= 150) {
clearInterval(direction);
direction = setInterval(moveLeft, 5);
} else {
x += 1;
box.style.left = x + "px";
}
}
function moveLeft() {
if (x <= 0) {
clearInterval(direction);
direction = setInterval(moveRight, 5);
} else {
x -= 1;
box.style.left = x + "px";
}
}
})();
body {
background-color: #246;
}
#container {
width: 200px;
height: 50px;
background: #268;
position: relative;
}
#box {
width: 50px;
height: 50px;
background: #2ac;
position: absolute;
}
<!DOCTYPE html>
<html>
<head>
<title>Move</title>
</head>
<body>
<div id="container">
<div id="box">
</div>
</div>
</body>
</html>

TypeError: Cannot read property 'innerHTML' of null

I am trying to retain the best time value under the id "bestTime", but I keep on getting the following error in Chrome: Cannot read property 'innerHTML' of null at showBestTime.
Not sure what I am doing wrong, I have attached the code below. I am trying to process the best time in the function showBestTime. Thanks in advance!
<html>
<head>
<title>Reaction tester</title>
</head>
<style type="text/css">
#page-container{
width: 1000px;
margin: 0 auto;
height: 800px;
}
body{
margin: 0;
padding: 0;
font-family: Helvetica, Arial, freesans, sans-serif;
}
#shape{
width: 200px;
height: 200px;
background-color: red;
display: none;
position: relative;
}
.time{
font-weight: bold;
}
</style>
<body>
<div id="page-container">
<h1>Test Your Reactions!</h1>
<p>Click on the boxes and circles as quickly as you can!</p>
<p class="time">Your time: <span id="timeTaken"></span></p>
<p class="time">Best time: <span id="bestTime">10</span>s</p>
<div id="shape"></div>
</div>
<script type="text/javascript">
var start=new Date().getTime();
function getRandomColor() {
var letters= "0123456789ABCDEF";
var color= "#";
for (var i=0; i<6; i++) {
color +=letters[Math.floor(Math.random()*16)];
}
return color;
}
function makeShapeAppear(){
var top=Math.random()*400;
var left=Math.random()*800;
var width=(Math.random()*400)+100;
if(Math.random()>0.5){ document.getElementById("shape").style.borderRadius="50%";
} else{
document.getElementById("shape").style.borderRadius="0";
} document.getElementById("shape").style.backgroundColor=getRandomColor();
document.getElementById("shape").style.top=top+"px";
document.getElementById("shape").style.left=left+"px"; document.getElementById("shape").style.width=width+"px"; document.getElementById("shape").style.height=width+"px";
document.getElementById("shape").style.display="block";
start=new Date().getTime();
}
function appearAfterDelay(){
setTimeout(makeShapeAppear, (Math.random() * 2000));
}
function showBestTime(y){ if(y<document.getElementById("besttime").innerHTML){
document.getElementById("besttime").innerHTML=y;
}
}
appearAfterDelay();
document.getElementById("shape").onclick=function(){
document.getElementById("shape").style.display="none";
var end=new Date().getTime();
var timeTaken=(end-start)/1000; document.getElementById("timeTaken").innerHTML=timeTaken+"s";
appearAfterDelay();
showBestTime(timeTaken);
}
</script>
</body>
</html>
You have made a spelling mistake in your selector. You have provided besttime as your selector instead of bestTime. I have added the working code along with.
<html>
<head>
<title>Reaction tester</title>
</head>
<style type="text/css">
#page-container {
width: 1000px;
margin: 0 auto;
height: 800px;
}
body {
margin: 0;
padding: 0;
font-family: Helvetica, Arial, freesans, sans-serif;
}
#shape {
width: 200px;
height: 200px;
background-color: red;
display: none;
position: relative;
}
.time {
font-weight: bold;
}
</style>
<body>
<div id="page-container">
<h1>Test Your Reactions!</h1>
<p>Click on the boxes and circles as quickly as you can!</p>
<p class="time">Your time: <span id="timeTaken"></span></p>
<p class="time">Best time: <span id="bestTime">10</span>s</p>
<div id="shape"></div>
</div>
<script type="text/javascript">
var start = new Date().getTime();
function getRandomColor() {
var letters = "0123456789ABCDEF";
var color = "#";
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
function makeShapeAppear() {
var top = Math.random() * 400;
var left = Math.random() * 800;
var width = (Math.random() * 400) + 100;
if (Math.random() > 0.5) {
document.getElementById("shape").style.borderRadius = "50%";
} else {
document.getElementById("shape").style.borderRadius = "0";
}
document.getElementById("shape").style.backgroundColor = getRandomColor();
document.getElementById("shape").style.top = top + "px";
document.getElementById("shape").style.left = left + "px";
document.getElementById("shape").style.width = width + "px";
document.getElementById("shape").style.height = width + "px";
document.getElementById("shape").style.display = "block";
start = new Date().getTime();
}
function appearAfterDelay() {
setTimeout(makeShapeAppear, (Math.random() * 2000));
}
function showBestTime(y) {
if (y < document.getElementById("bestTime").innerHTML) {
document.getElementById("bestTime").innerHTML = y;
}
}
appearAfterDelay();
document.getElementById("shape").onclick = function () {
document.getElementById("shape").style.display = "none";
var end = new Date().getTime();
var timeTaken = (end - start) / 1000;
document.getElementById("timeTaken").innerHTML = timeTaken + "s";
appearAfterDelay();
showBestTime(timeTaken);
}
</script>
</body>
</html>
You have span:
<span id="bestTime">
and you query it with
document.getElementById("besttime")
and bestTime is not equal to besttime, so change to:
document.getElementById("bestTime")

play animation on matching pairs in memory game

I'm creating a memory game for my web assignment at uni and I am stuck on how to get my animation playing on match on top of the cards that match.
At the moment, I have been able to get the animation to play on click of the memory_board div, but only works once.
So question 1 - How do you get the animation to work every time you click on the Memory_board div.(It only works once atm, and have to refresh the page to play it again)
My code for the animation to work is:
.sprite {
width:96px;
height:96px;
position: relative;
margin:15px;
}
.toon{
background: url(explode.png);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type='text/javascript' src='jquery.animateSprite.js'></script>
<script>//sparkle effect: http://www.rigzsoft.co.uk/how-to-implement-animated-sprite-sheets-on-a-web-page/
$(document).ready(function(){
$("#memory_board").click(function animation(){
$(".toon").animateSprite({
columns: 10,
totalFrames: 50,
duration: 1000,
});
});
});
</script>
<body>
<div class = "grid_10">
<div id="memory_board"></div>
<script>newBoard();</script>
<div style="position: relative; height: 110px;">
<div class="sprite toon"></div>
</div>
</div>
</body>
Question 2 - How will I place this animation over top of each card?
The layout of the board is by float in the memory_boarddiv, where the images are in an array and called up in the function tile.innerHTML = '<img src="' + val + '.png"/>';
Here is the full coding for the board:
div#memory_board{
background: -webkit-radial-gradient(#FFF, #CC99FF); /* For Safari 5.1 to 6.0 */
background: -o-radial-gradient(#FFF, #CC99FF); /* For Opera 11.1 to 12.0 */
background: -moz-radial-gradient(#FFF, #CC99FF); /* For Firefox 3.6 to 15 */
background: radial-gradient(#FFF, #CC99FF); /* Standard syntax (must be last) */
border:#FF0066 10px ridge;
width:510px;
height:405px;
padding:24px;
}
div#memory_board > div{
background:url(tile_background.png) no-repeat;
border:#000 1px solid;
width:45px;
height:45px;
float:left;
margin:7px;
padding:20px;
cursor:pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>Memory Card Game</title>
<meta http-equiv="Content-type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="reset.css" />
<link rel="stylesheet" type="text/css" href="text.css" />
<link rel="stylesheet" type="text/css" href="960.css" />
<link rel="stylesheet" type="text/css" href="mystyles.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type='text/javascript' src='jquery.animateSprite.js'></script>
<script> //developphp.com tutorial
var memory_array = ['A','A','B','B','C','C','D','D','E','E','F','F','G','G','H','H','I','I','J','J'];
var memory_values = [];
var memory_tile_ids = [];
var tiles_flipped = 0;
var turns = 0
var matches = 0
Array.prototype.memory_tile_shuffle = function(){
var i = this.length, j, temp;
while(--i > 0){
j = Math.floor(Math.random() * (i+1));
temp = this[j];
this[j] = this[i];
this[i] = temp;
}
}
function newBoard(){
tiles_flipped = 0;
var output = '';
memory_array.memory_tile_shuffle();
for(var i = 0; i < memory_array.length; i++){
output += '<div id="tile_'+i+'" onclick="memoryFlipTile(this,\''+memory_array[i]+'\')"></div>';
}
document.getElementById('memory_board').innerHTML = output;
//fade in
$(document).ready(function () {
$('#memory_board > div').hide().fadeIn(1500).delay(6000)
});
resetTime();
turns = 0;
document.getElementById('Count').innerHTML = 0;
matches = 0;
document.getElementById('matchNumber').innerHTML = 0;
}
function memoryFlipTile(tile,val){
startTimer();
playClick();
if(tile.innerHTML == "" && memory_values.length < 2){
tile.style.background = '#FFF';
tile.innerHTML = '<img src="' + val + '.png"/>';
if(memory_values.length == 0){
memory_values.push(val);
memory_tile_ids.push(tile.id);
} else if(memory_values.length == 1){
memory_values.push(val);
memory_tile_ids.push(tile.id);
if(memory_values[0] == memory_values[1]){
tiles_flipped += 2;
//sound
playMatch();
//animation
//number of clicks
turns = turns + 1;
document.getElementById("Count").innerHTML = turns;
//number of matches
matches = matches + 1;
document.getElementById("matchNumber").innerHTML = matches;
// Clear both arrays
memory_values = [];
memory_tile_ids = [];
// Check to see if the whole board is cleared
if(tiles_flipped == memory_array.length){
playEnd();
Alert.render("Congratulations! Board Cleared");
//resetTime()
//stopCount();
document.getElementById('memory_board').innerHTML = "";
newBoard();
}
} else {
function flipBack(){
// Flip the 2 tiles back over
var tile_1 = document.getElementById(memory_tile_ids[0]);
var tile_2 = document.getElementById(memory_tile_ids[1]);
tile_1.style.background = 'url(tile_background.png) no-repeat';
tile_1.innerHTML = "";
tile_2.style.background = 'url(tile_background.png) no-repeat';
tile_2.innerHTML = "";
//number of clicks
turns = turns + 1;
document.getElementById("Count").innerHTML = turns;
//clickNumber()
// Clear both arrays
memory_values = [];
memory_tile_ids = [];
}
setTimeout(flipBack, 700);
}
}
}
}
</script>
<body>
<div class = "grid_10">
<div id="memory_board"></div>
<script>newBoard();</script>
<div style="position: relative; height: 110px;">
<div class="sprite toon"></div>
</div>
</div>
</body>
Question 3 - How will I get to play this animation only on match, on top of the cards that have matched.
I'm guessing this is done by putting it into the memoryFlipTile function under the //animation where the sound and match number change upon a match found :
function memoryFlipTile(tile,val){
startTimer();
playClick();
if(tile.innerHTML == "" && memory_values.length < 2){
tile.style.background = '#FFF';
tile.innerHTML = '<img src="' + val + '.png"/>';
if(memory_values.length == 0){
memory_values.push(val);
memory_tile_ids.push(tile.id);
} else if(memory_values.length == 1){
memory_values.push(val);
memory_tile_ids.push(tile.id);
if(memory_values[0] == memory_values[1]){
tiles_flipped += 2;
//sound
playMatch();
//animation
//number of clicks
turns = turns + 1;
document.getElementById("Count").innerHTML = turns;
//number of matches
matches = matches + 1;
document.getElementById("matchNumber").innerHTML = matches;
// Clear both arrays
memory_values = [];
memory_tile_ids = [];
}
In case these snippets are confusing and you want the whole picture, here is the full script:
body{
background:#FFF;
font-family: Cooper Black;
}
h1{
font-family: Cooper Black;
text-align: center;
font-size: 64px;
color: #FF0066;
}
footer{
height: 150px;
background: -webkit-linear-gradient(#99CCFF, #FFF); /* For Safari 5.1 to 6.0 */
background: -o-linear-gradient(#99CCFF, #FFF); /* For Opera 11.1 to 12.0 */
background: -moz-linear-gradient(#99CCFF, #FFF); /* For Firefox 3.6 to 15 */
background: linear-gradient(#99CCFF, #FFF); /* Standard syntax (must be last) */
}
div#memory_board{
background: -webkit-radial-gradient(#FFF, #CC99FF); /* For Safari 5.1 to 6.0 */
background: -o-radial-gradient(#FFF, #CC99FF); /* For Opera 11.1 to 12.0 */
background: -moz-radial-gradient(#FFF, #CC99FF); /* For Firefox 3.6 to 15 */
background: radial-gradient(#FFF, #CC99FF); /* Standard syntax (must be last) */
border:#FF0066 10px ridge;
width:510px;
height:405px;
padding:24px;
}
div#memory_board > div{
background:url(tile_background.png) no-repeat;
border:#000 1px solid;
width:45px;
height:45px;
float:left;
margin:7px;
padding:20px;
cursor:pointer;
}
alert{
background: #FF0066;
}
button{
font-family: Cooper Black;
font-size: 20px;
color: #FF0066;
background: #5CE62E;
border: #C2E0FF 2px outset;
border-radius: 25px;
padding: 10px;
cursor: pointer;
}
input#txt{
background: yellow;
color: #FF0066;
font-family: Times New Roman;
font-size: 84px;
height: 150px;
width: 150px;
border-radius: 100%;
text-align: center;
border: none;
}
input#pause{
font-family: Cooper Black;
font-size: 18px;
color: #FF0066;
background: #C2E0FF;
border: #C2E0FF 2px outset;
border-radius: 25px;
padding: 10px;
cursor: pointer;
margin-top: 10px;
}
div.goes{
text-align: center;
border: #C2E0FF 5px double;
height: 160px;
width: 120px;
margin-top: 48px;
margin-left: 5px;
}
div.matches{
text-align: center;
border: #C2E0FF 5px double;
height: 160px;
width: 120px;
margin-top: 30px;
margin-left: 10px;
}
p{
font-size: 28px;
}
span{
font-family: Times New Roman;
font-size: 84px;
}
.sprite {
width:96px;
height:96px;
position: relative;
margin:15px;
}
.toon{
background: url(explode.png);
}
}
#dialogoverlay{
display: none;
opacity: 0.8;
position: fixed;
top: 0px;
left: 0px;
background: #FFF;
width: 100%;
z-index: 10;
}
#dialogbox{
display: none;
position: fixed;
background: #FF0066;
border-radius:7px;
width:400px;
z-index: 10;
}
#dialogbox > div{ background: #FFF; margin:8px; }
#dialogbox > div > #dialogboxhead{ background: linear-gradient(#99CCFF, #FFF); height: 40px; color: #CCC; }
#dialogbox > div > #dialogboxbody{ background: #FFF; color: #FF0066; font-size: 36px; text-align:center;}
#dialogbox > div > #dialogboxfoot{ background: linear-gradient(#FFF, #99CCFF); padding-bottom: 20px; text-align:center; }
<!DOCTYPE html>
<html>
<head>
<title>Memory Card Game</title>
<meta http-equiv="Content-type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="reset.css" />
<link rel="stylesheet" type="text/css" href="text.css" />
<link rel="stylesheet" type="text/css" href="960.css" />
<link rel="stylesheet" type="text/css" href="mystyles.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type='text/javascript' src='jquery.animateSprite.js'></script>
<script> //developphp.com tutorial
var memory_array = ['A','A','B','B','C','C','D','D','E','E','F','F','G','G','H','H','I','I','J','J'];
var memory_values = [];
var memory_tile_ids = [];
var tiles_flipped = 0;
var turns = 0
var matches = 0
Array.prototype.memory_tile_shuffle = function(){
var i = this.length, j, temp;
while(--i > 0){
j = Math.floor(Math.random() * (i+1));
temp = this[j];
this[j] = this[i];
this[i] = temp;
}
}
function newBoard(){
tiles_flipped = 0;
var output = '';
memory_array.memory_tile_shuffle();
for(var i = 0; i < memory_array.length; i++){
output += '<div id="tile_'+i+'" onclick="memoryFlipTile(this,\''+memory_array[i]+'\')"></div>';
}
document.getElementById('memory_board').innerHTML = output;
//fade in
$(document).ready(function () {
$('#memory_board > div').hide().fadeIn(1500).delay(6000)
});
resetTime();
turns = 0;
document.getElementById('Count').innerHTML = 0;
matches = 0;
document.getElementById('matchNumber').innerHTML = 0;
}
function memoryFlipTile(tile,val){
startTimer();
playClick();
if(tile.innerHTML == "" && memory_values.length < 2){
tile.style.background = '#FFF';
tile.innerHTML = '<img src="' + val + '.png"/>';
if(memory_values.length == 0){
memory_values.push(val);
memory_tile_ids.push(tile.id);
} else if(memory_values.length == 1){
memory_values.push(val);
memory_tile_ids.push(tile.id);
if(memory_values[0] == memory_values[1]){
tiles_flipped += 2;
//sound
playMatch();
//animation
//number of clicks
turns = turns + 1;
document.getElementById("Count").innerHTML = turns;
//number of matches
matches = matches + 1;
document.getElementById("matchNumber").innerHTML = matches;
// Clear both arrays
memory_values = [];
memory_tile_ids = [];
// Check to see if the whole board is cleared
if(tiles_flipped == memory_array.length){
playEnd();
Alert.render("Congratulations! Board Cleared");
//resetTime()
//stopCount();
document.getElementById('memory_board').innerHTML = "";
newBoard();
}
} else {
function flipBack(){
// Flip the 2 tiles back over
var tile_1 = document.getElementById(memory_tile_ids[0]);
var tile_2 = document.getElementById(memory_tile_ids[1]);
tile_1.style.background = 'url(tile_background.png) no-repeat';
tile_1.innerHTML = "";
tile_2.style.background = 'url(tile_background.png) no-repeat';
tile_2.innerHTML = "";
//number of clicks
turns = turns + 1;
document.getElementById("Count").innerHTML = turns;
//clickNumber()
// Clear both arrays
memory_values = [];
memory_tile_ids = [];
}
setTimeout(flipBack, 700);
}
}
}
}
//timer
var c = 0;
var t;
var timer_is_on = 0;
function timedCount() {
document.getElementById('txt').value = c;
c = c+1;
t = setTimeout(timedCount, 1000);
}
function startTimer() {
if (!timer_is_on) {
timer_is_on = 1;
timedCount();
}
}
function stopCount() {
clearTimeout(t);
timer_is_on = 0;
}
function resetTime(){
clearTimeout(t);
timer_is_on = 0;
c = 0
document.getElementById('txt').value = 0
}
//sound effects /*sounds from http://www.freesfx.co.uk*/
function playClick(){
var sound=document.getElementById("click");
sound.play();
}
function playMatch(){
var sound=document.getElementById("match_sound");
sound.play();
}
function playEnd(){
var sound=document.getElementById("finished");
sound.play();
}
//custom alert developphp.com tutorial
function CustomAlert(){
this.render = function(dialog){
var winW = window.innerWidth;
var winH = window.innerHeight;
var dialogoverlay = document.getElementById('dialogoverlay');
var dialogbox = document.getElementById('dialogbox');
dialogoverlay.style.display = "block";
dialogoverlay.style.height = winH+"px";
dialogbox.style.left = (winW/2) - (400 * .5)+"px";
dialogbox.style.top = "200px";
dialogbox.style.display = "block";
document.getElementById('dialogboxhead').innerHTML = "";
document.getElementById('dialogboxbody').innerHTML = dialog;
document.getElementById('dialogboxfoot').innerHTML = '<button onclick="Alert.ok()">New Game</button>';
}
this.ok = function(){
document.getElementById('dialogbox').style.display = "none";
document.getElementById('dialogoverlay').style.display = "none";
}
}
var Alert = new CustomAlert();
</script>
<script>//sparkle effect: http://www.rigzsoft.co.uk/how-to-implement-animated-sprite-sheets-on-a-web-page/
$(document).ready(function(){
$("#memory_board").click(function animation(){
$(".toon").animateSprite({
columns: 10,
totalFrames: 50,
duration: 1000,
});
});
});
</script>
</head>
<body>
<audio id = "click" src = "click.mp3" preload = "auto"></audio>
<audio id = "match_sound" src = "match.mp3" preload = "auto"></audio>
<audio id = "finished" src = "finished.wav" preload = "auto"></audio>
<div id = "dialogoverlay"></div>
<div id = "dialogbox">
<div>
<div id = "dialogboxhead"></div>
<div id = "dialogboxbody"></div>
<div id = "dialogboxfoot"></div>
</div>
</div>
<div class = "container_16">
<div id = "banner" class = "grid_16">
<p><br></p>
<h1>Memory</h1>
</div>
<div class = "grid_3">
<input type="text" id="txt" value="0"/>
<p><br></p>
<p><br></p>
<div class = "goes">
<p>Turns <br><span id = "Count">0</span></p>
</div>
</div>
<div class = "grid_10">
<div id="memory_board"></div>
<script>newBoard();</script>
<div style="position: relative; height: 110px;">
<div class="sprite toon"></div>
</div>
</div>
<div class = "grid_3">
<button id = "new_game" onclick="newBoard()">New Game</button>
<input type="button" id="pause" value="Pause Game" onclick="stopCount()">
<p><br></p>
<p><br></p>
<p><br></p>
<div class = "matches">
<p>Matches <br><span id = "matchNumber">0</span></p>
</div>
</div>
</div>
<footer> </footer>
</body>
</html>

Categories