How do I pass arguments to a 'setTimeout' function? - javascript

How can I make these functions use variables for the id? I can't get the setTimeout to work when I do.
<script type="text/javascript">
function changeBarAWidth() {
var bar = document.getElementById('firstbar');
bar.style.width = lengthA + "px";
}
function increaseBarA() {
if (lengthA < fullBarA) {
changeBarAWidth();
lengthA = (lengthA + 2);
setTimeout("increaseBarA()", 10); // <-- How do I pass "firstbar"?
}
}
function resetLengthA() {
lengthA = 0;
changeBarAWidth();
}
var barA = 'firstbar';
var percentA = 80;
var fullBarA = (percentA * 2);
var lengthA = 0;
</script>
<style type="text/css">
ul {
list-style-type: none;
}
.bar {
width: 50px;
height: 5px;
background-color: red;
}
.back {
background-color: black;
height: 5px;
width: 200px;
}
</style>
</head>
<body onload="increaseBarA()">
<ul>
<li class="back">
<p class="bar" id="firstbar"></p>
</li>
</ul>
<button onClick="increaseBarA()">Test Change</button>
<button onClick="resetLengthA()">Reset</button>

I had to use a setTimeout(function() { YourFuncwith(params); }, 10);.
Here is the script. If anybody would like copy, please do:
// functions to show poll reults, div width increase every tenth of a second,
// looks like poll is sliding.
// length is name of global length variable you declare, mine are at bottom of script
// I will use php to dynaimcally give variable values based on poll results.
function changeBarWidth(id, length) {
var bar = document.getElementById(id);
bar.style.width = length + "px";
}
/* max is how long you want the poll to slide to, my background is 200px
* so I set to (percent*2);
*/
function increaseBar(id, max, length) {
var full = max;
if (length < full) {
changeBarWidth(id, length);
length = (length + 2);
setTimeout(function() {
increaseBar(id, max, length);
}, 10);
}
}
var barA = 'firstbar';
var percentA = 80;
var fullBarA = (percentA * 2);
var lengthA = 0;
var lengthB = 0;
ul {
list-style-type: none;
}
.bar {
width: 50px;
height: 5px;
background-color: red;
}
.back {
background-color: black;
height: 5px;
width: 200px;
}
<body onload="increaseBar(barA, percentA, lengthA)">
<div id="pollresults">
<ul>
<li class="back">
<p class="bar" id="firstbar"></p>
</li>
<li class="back">
<p class="bar" id="secondbar"></p>
</li>
</ul>
</div>
<button onClick="increaseBar('secondbar',fullBarA,lengthB)">Test Change</button>
</body>

Related

How to retain the last dragged position of the range slider even on page refresh in javascript

I am having webpage consisting of a range slider which is having three values 1,2,3 for every value there will be change in image,some phrase now my requirement is on page refresh the range slider is setting to the one I dont want it I want it to restore its last dragged position along with image and phrase even on page refresh
My CSS code:
<style>
.rangeslider {
width: 50%;
margin: 0 auto;
position: absolute;
}
.myslider {
-webkit-appearance: none;
background: white;
width: 100%;
height: 20px;
opacity: 0.8;
margin-top: 180px;
}
.myslider::-webkit-slider-thumb {
-webkit-appearance: none;
cursor: pointer;
background: #000080;
width: 33%;
height: 20px;
}
.myslider:hover {
opacity: 1;
}
.image {
position: relative;
width: 400px;
margin: 0 auto;
}
.image>img {
position: absolute;
display: none;
}
.image>img.visible,
.image>img:first-child {
display: block;
}
#sliderOutput>div {
display: none;
}
#sliderOutput>div.visible,
#sliderOutput>div:first-child {
display: block;
}
</style>
My Html code:
<div class="image mt-3 mb-3" id="sliderImages">
<img src="/static/images/1.jpg" width="400" height="180"><!--Image1-->
<img src="/static/images/2.jpg" width="400" height="180"><!--Image2-->
<img src="/static/images/3.jpg" width="400" height="180"><!--Image3-->
</div><br><!-- End of Image sliding-->
<!--Range slider starts-->
<div class="rangeslider">
<input type="range" min="1" max="3" value="1" class="myslider" id="sliderRange" onload="showVal(this.value)">
<div class="container">
<div id="sliderOutput">
<div class="col-4" id="range_1">
<h6 class="display-6 mt-3" ><b><center>Starting from scratch</center></b></h6>
<p class="demo"><center>I'm designing the room </p>
</div>
<div class="col-4" id="range_2">
<h6 class="display-6 mt-3"><b>Somewhere in Between</b></h6>
<p class="demo">I'm designing around a few pieces I already own</p>
</div>
<div class="col-4" id="range_3">
<h6 class="display-6 mt-3"><b>Mostly furnished</b></h6>
<p class="demo">I want to put the finishing touches on my room</p>
</div>
</div><!--End of Range slider-->
My Js code:
window.onload = function()
{
var imagePath = "../static/images/";
var localStorageSliderNumber;
var localStorageImagePath;
if (window.localStorage.getItem('sliderValue') != null) {
localStorageSliderNumber = window.localStorage.getItem('sliderValue');
} else {
window.localStorage.setItem('sliderValue', '1');
localStorageSliderNumber = 1;
}
if (window.localStorage.getItem('imagePath') != null) {
imagePath = imagePath + window.localStorage.getItem('imagePath') + ".jpg";
}
var rangeslider = document.getElementById("sliderRange");
var output = document.getElementById("sliderOutput");
var images = document.getElementById("sliderImages");
rangeslider.addEventListener('input', function() {
for (var i = 0; i < output.children.length; i++) {
output.children[i].style.display = 'none';
images.children[i].style.display = 'none';
}
i = Number(this.value) - 1;
output.children[i].style.display = 'block';
images.children[i].style.display = 'block';
window.localStorage.setItem('imagepath', rangeslider.getAttribute('value'));
window.localStorage.setItem('sliderValue', (i+1));
});
}
Here I am storing the value in the local storage i.e slidervalue but now I want to retain the last dragged position of the rangeslider along with phrase and image
[1]: https://codepen.io/lakshmi123__/pen/abzYeLP
Here you go.
You just need to call your setter methods on load as well. What I've done is, I've segregated the common code for setting the data separately and called it both on load and on value change. Here's an updated code.
window.onload = function() {
var imagePath = "../static/images/";
var localStorageSliderNumber;
var localStorageImagePath;
if (window.localStorage.getItem('sliderValue') != null) {
localStorageSliderNumber = window.localStorage.getItem('sliderValue');
} else {
window.localStorage.setItem('sliderValue', '1');
localStorageSliderNumber = 1;
}
if (window.localStorage.getItem('imagePath') != null) {
imagePath = imagePath + window.localStorage.getItem('imagePath') + ".jpg";
}
var rangeslider = document.getElementById("sliderRange");
var output = document.getElementById("sliderOutput");
var images = document.getElementById("sliderImages");
rangeslider.value = localStorageSliderNumber;
//The common line of code extracted into a method
setData(rangeslider, output, images, localStorageSliderNumber);
rangeslider.addEventListener('input', function() {
//call the method once again
setData(rangeslider, output, images, this.value);
});
}
function setData(rangeslider, output, images, value) {
for (var i = 0; i < output.children.length; i++) {
output.children[i].style.display = 'none';
images.children[i].style.display = 'none';
}
i = Number(value) - 1;
output.children[i].style.display = 'block';
images.children[i].style.display = 'block';
window.localStorage.setItem('imagepath', rangeslider.getAttribute('value'));
window.localStorage.setItem('sliderValue', (i + 1));
window.localStorage.setItem('sliderPosition', (i + 1))
}
Here's the Updated Pen

Changing onClick of a span when it is clicked using JS

I've created a program that randomly spawns a span (in the form of a circle). I want to change the onClick of the previous span class when clicked on.
I've already attempted to set the id of the new span element to something that creates recursively (span.id = "a" + t; t++;) or something like that.
<!doctype html>
<link href="https://fonts.googleapis.com/css?
family=Montserrat" rel="stylesheet">
<link rel="icon" type="image/jpg" href="/vNidjVg-
_400x400.jpg"/>
<style>
body{
background-color: #010417;
font-family: 'Montserrat', sans-serif;
}
#keyframes a{
0% {opacity: 0;}
100%{opacity: 1;}
}
button{
background-color: #010417;
border-radius: 10px;
border: 4px solid white;
color: white;
padding: 10px 26px;
font-size: 20px;
}
</style>
<div id="myDIV">
<script>
document.title = prompt("I don't know what to make the
document's title, so what do you want it to be called?");
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min + 1) ) + min;
}
var but = 2;
var x = 0
function button(){
if(but === 2){
myFunction();
but = 0;
}else{}
}
var t = 0;
var q = -1;
function myFunction() {
var para = document.createElement("SPAN");
para.style.position = "absolute";
x = getRndInteger(0, (window.innerWidth - 60))
para.style.left = x + "px"
var p = getRndInteger(0, (window.innerHeight - 60))
para.style.top = p + "px"
para.style.display = "inline-block;"
para.style.height = "50px"
para.style.width = "50px"
para.style.backgroundColor="red"
para.style.borderRadius = "50px"
para.style.border = "1px solid black"
para.style.animation = "1s a linear"
para.id = "a" + t;
document.getElementById("a" + q).onclick=f
q++
t++;
para.onclick=myFunction
document.getElementById("myDIV").appendChild(para);
}
function f(){}
</script>
</div>
<center>
<button class="1" id="button" onClick="button();">Start</button></center>
I expect the output of this to be the previous span class to be disabled (onclick set to f())
Firstly, you should define as much of the style of your elements as possible in CSS instead of defining it in Javascript.
Secondly, when a onclick is called in JS, the first parameter of the function should be event which is a representation of the click event that just appeared. Here in the onclick you can get the clicked element with event.toElement which allows you to redefine onclick.
I think what you are trying to do should look like something like this :
var container = document.getElementById("container");
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min + 1) ) + min;
}
function spawn() {
var span = document.createElement("SPAN");
span.style.left = getRndInteger(30, (container.offsetWidth - 30)) + "px";
span.style.top = getRndInteger(30, (container.offsetHeight - 30)) + "px";
span.onclick = fA;
container.appendChild(span);
}
function fA(event) {
var span = event.toElement
alert("first click here");
span.onclick = fB;
}
function fB(event) {
alert("second click here");
}
div#container {
width: 300px;
height: 300px;
}
div#container span {
width: 30px;
height: 30px;
position: absolute;
border-radius: 100%;
background-color: red;
}
<button onclick="spawn()">Spawn a span</button>
<div id="container"></div>

Function to count number of line breaks acts differently on $(window).on('resize') and $(document).ready

I have a function which counts the number of line breaks in a div, depending on the width of the window. While the functions works fine when placed in the $(window).on('resize') function, it does not work when put in $(document).ready() function. I want it to work right on page load, and also window resize, how do I support both?
JSFiddle
Javascript/jQuery:
// functions called in both document.ready() and window.resize
$(document).ready(function(){
var lineCount = getLineCount();
postItems(lineCount);
$('.answer').text("Ready");
});
$(window).on('resize', function(){
var lineCount = getLineCount();
postItems(lineCount);
$('.answer').text("Number of lines: " + lineCount);
});
// calculates the amount of lines required to hold the items
function getLineCount() {
var lineWidth = $('.line').width();
var itemWidthSum = 0;
var lineCount=1;
$('.item').each(function(index, element) {
if((lineWidth - itemWidthSum) > ($(element).outerWidth())) {
itemWidthSum = itemWidthSum + $(element).outerWidth();
} else {
lineCount++;
itemWidthSum = $(element).outerWidth();
}
});
return lineCount;
}
// overlays rows for the amount of linebreaks
function postItems(lineCount){
var container = $('<div />');;
for(var i = 1; i <= lineCount; i++) {
container.append('<div class="line">' + i + '</div>');
}
$('.line-wrap').html(container);
}
You'll see at the start of the page, it incorrectly shows 17 lines, and then once you resize it will show the correct amount.
The issue lies in the first line of getLineCount(). Originally you had
var lineWidth = $('.line').width();
but no elements with the class "line" exist yet on your page (since they get added in your postItems() method. I changed it to
var lineWidth = $(".container").width();
instead, and now your code should be working. Snippet posted below:
$(document).ready(function(){
var lineCount = getLineCount();
postItems(lineCount);
$('.answer').text("Ready");
});
$(window).on('resize', function(){
var lineCount = getLineCount();
postItems(lineCount);
$('.answer').text("Number of lines: " + lineCount);
});
// calculates the amount of lines required to hold the items
function getLineCount() {
var lineWidth = $('.container').width();
var itemWidthSum = 0;
var lineCount=1;
$('.item').each(function(index, element) {
if((lineWidth - itemWidthSum) > ($(element).outerWidth())) {
itemWidthSum = itemWidthSum + $(element).outerWidth();
} else {
lineCount++;
itemWidthSum = $(element).outerWidth();
}
});
return lineCount;
}
// overlays rows for the amount of linebreaks
function postItems(lineCount){
var container = $('<div />');;
for(var i = 1; i <= lineCount; i++) {
container.append('<div class="line">' + i + '</div>');
}
$('.line-wrap').html(container);
}
body {
text-align:center;
}
.answer {
position: fixed;
left: 0;
bottom: 0;
}
.container {
position: relative;
width: 50%;
margin: 0 auto;
border: 1px solid #e8e8e8;
display: inline-block;
}
.item {
height: 50px;
padding:0 10px;
background-color: #aef2bd;
float: left;
opacity:0.2;
white-space: nowrap;
}
.line-wrap {
position: absolute;
border: 1px solid red;
width: 100%;
height: 100%;
top:0; left: 0;
}
.line {
height: 50px;
width: 100%;
background-color: blue;
opacity:0.5;
color: white;
transition: all 0.5s ease;
}
.line:hover {
background-color: yellow;
color: #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="item-wrap">
<div class="item">Computer Science</div>
<div class="item">Language</div>
<div class="item">Marketing</div>
<div class="item">Biology</div>
<div class="item">Computer Science</div>
<div class="item">Language</div>
<div class="item">Marketing</div>
<div class="item">Biology</div>
<div class="item">Computer Science</div>
<div class="item">Language</div>
<div class="item">Marketing</div>
<div class="item">Biology</div>
<div class="item">Computer Science</div>
<div class="item">Language</div>
<div class="item">Marketing</div>
<div class="item">Biology</div>
</div>
<div class="line-wrap">
</div>
</div>
<h1 class="answer"></h1>

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