https://codepen.io/anon/pen/EOrRXo
This is my code so far. It just uses JS to generate a bunch of styled divs. I don't know how to input a picture instead of a string to fill in my divs. They all have values that I add up to generate each players' score to use bitwise "&" calculation to determine when someone has won. There's a play again button that works but it's broken for you because the image is local. Also it's extreme so it's spinning and I'm sorry if that annoys you.
HTML:
<!DOCTYPE html>
<html>
<head>
<title>EXTREME TIC TAC TOE</title>
<link type="text/css" rel="stylesheet" href="css/style.css">
<script src="js/script.js"></script>
</head>
<body onload = "startGame();">
<h2 id="game-message"> Tic Tac Toe </h2>
<div id="game-board">
</div>
<div id="restartButton" >
<img src="img/lets-play.gif" id="button" onclick="restartGame();">
</div>
</body>
</html>
CSS
/* CSS */
* {margin: 0; padding: 0; user-select: none; text-transform: uppercase;}
body {background-image: url('../img/name.type'); }
h2#game-message
{
font-size: 60px;
font-family: Tahoma;
margin-bottom: 15px;
text-align: center;
}
div#game-board
{
overflow: hidden;
margin: 20px auto;
width:870px;
}
div[id^="row-"] {clear: both;}
div [id^="row-"] div
{
//border: 30px solid plum;
height: 270px;
width: 270px;
float: left;
text-align: center;
font-family: Tahoma;
font-size: 175px;
border-width: 15px;
border-style: solid;
border-image: url('../img/border.jpg') 25% repeat;
}
div#row-1 div {border-top: none;}
div#row-3 div {border-bottom: none;}
div[id^="row-"] div:first-child {border-left: none}
div[id^="row-"] div:last-child {border-right: none}
#button
{
color: white;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
border-width: 5px;
border-style: solid;
border-image: url('../img/borderr.png') 25% round;
}
#restartButton
{
position: absolute;
left: 880px;
top: 1075px;
}
#keyframes rotation
{
from {
transform: rotate(0deg);
}
to {
transform: rotate(359deg);
}
}
#keyframes slide {
0% {left: 0;}
100% { left: 1500px;}
}
#game-board
{
position: relative;
}
JS
//JAVASCRIPT
var markers = ["X", "O"];
//var players = [];
var players = ["Max", "Dennis"];
var totals = [];
var winCodes = [7,56,73,84,146,273,292,448];
var whoseTurn = 0;
var gameOver = false;
var speed = [2, 2];
// Play again button
function restartGame()
{
startGame();
}
function startGame() // Choose your names, and display them in the header message.
{
// makes board spin initially
document.getElementById("game-board").style.animation = "rotation 4s infinite linear";
//players[0] = prompt("Player 1 NAME:");
//players[1] = prompt("Player 2 NAME:");
var counter = 1;
var innerDivs = "";
for (i = 1; i <=3; i++)
{
innerDivs += '<div id="row-' + i + '">';
for (j = 1; j <= 3; j++)
{
innerDivs += '<div onclick="playGame(this,' + counter + ');"></div>';
counter *= 2;
}
innerDivs += '</div>';
}
document.getElementById("game-board").innerHTML = innerDivs;
totals = [0, 0];
gameOver = false;
document.getElementById("game-message").innerText = "IT'S YOUR TURN " + players[whoseTurn];
}
function playGame(clickedDiv, divValue)
{
if (!gameOver)
{
// changes speed depending on how many turns each player has done
speed[whoseTurn]++;
document.getElementById("game-board").style.animation = "rotation "+ 8 / speed[whoseTurn] + "s infinite linear";
// Adds X or O depending on whoseTurn
clickedDiv.innerText = markers[whoseTurn];
// adds up total each time a player "moves" to track a win condition
totals[whoseTurn] += divValue;
// calls isWin() function to see if someone won
if (isWin())
{
document.getElementById("game-message").innerText = "WOW VERY COOL " + players[whoseTurn] + " YOU WON";
document.getElementById("game-board").style.animation = "slide 2s forwards, rotation "+ 8 / speed[whoseTurn] + "s infinite linear";
}
else if (gameOver)
{
document.getElementById("game-message").innerText = "YOU BOTH FAILED";
}
else
{
// Switches turn each click
if (whoseTurn) whoseTurn = 0; else whoseTurn = 1;
// disables onclick tag after clicked so it cannot be used >1 times.
clickedDiv.attributes["0"].nodeValue = "";
// Displays text for which turn it is
document.getElementById("game-message").innerText = "IT'S YOUR TURN " + players[whoseTurn];
}
}
}
// win code logic
function isWin()
{
for (i = 0; i < winCodes.length; i++)
{
if ((totals[whoseTurn] & winCodes[i]) == winCodes[i]) {gameOver = true; return true;}
}
if (totals[0] + totals[1] == 511) {gameOver = true;}
return false;
}
You can start by replacing the markers array with (or creating a new array, such as markerImages) image elements.
Then replace clickedDiv.innerText with clickedDiv.innerHTML.
Related
I've just started a couple of days in web development.
I need help for - I have two texts in the HTML (p tag) on the same line, one linked to JS with an "ID" and the other to CSS with "Class" and by using keyframes, and I've been trying to add a static text on the same line that displays after the animated text.
I'm trying to output - Where the First text animates by default, and when JS actions are triggered, that is by clicking on the button, the second text should display a static text on the same line as the first text.
My code:
JavaScript
CSS
HTML
let secondText = document.getElementById("second-text");
let a = 1;
let b = 5;
let c = a + b;
let result = "";
function startAction() {
if (c <= 12) {
result = "December";
} else {
result = "Not-Exists";
}
secondText.textContent = result;
console.log(result);
}
#second-text {
margin: 30px;
font-size: 20px;
font-weight: 700;
}
.first-text {
margin: 30px;
font-size: 20px;
font-weight: 700;
animation: typing 10s steps(19) infinite;
overflow: hidden;
white-space: nowrap;
border-right: 2px solid #111;
width: 19ch;
}
#keyframes typing {
0% {
width: 0ch;
}
50% {
width: 19ch;
}
100% {
width: 0ch;
}
}
<p class="first-text" id="second-text">Welcome To My Page</p>
<button onclick="startAction()">Action</button>
Please, Help me figure out what went wrong in my code?
Is that what you are looking for ?
let secondText = document.getElementById("second-text");
let a = 1;
let b = 5;
let c = a + b;
let result = "";
function startAction() {
document.getElementById("second-text").classList.remove("first-text");
document.getElementById("second-text").classList.add("newClass");
if (c <= 12) {
result = "December";
} else {
result = "Not-Exists";
}
secondText.textContent = result;
console.log(result);
}
.first-text {
margin: 30px;
font-size: 20px;
font-weight: 700;
animation: typing 10s steps(19) infinite;
overflow: hidden;
white-space: nowrap;
border-right: 2px solid #111;
width: 19ch;
}
.newClass{
margin: 30px;
font-size: 20px;
font-weight: 700;
overflow: hidden;
white-space: nowrap;
width: 19ch;
}
#keyframes typing {
0% {
width: 0ch;
}
50% {
width: 19ch;
}
100% {
width: 0ch;
}
}
<p class="first-text" id="second-text">Welcome To My Page</p>
<button onclick="startAction()">Action</button>
I am making a typing program. Each letter is in its own div, which is broken into words.
For example, the word other would be written as:
<div class="word">
<div class="letter" id="l184"></div>
<div class="letter" id="l185">o</div>
<div class="letter" id="l186">t</div>
<div class="letter" id="l187">h</div>
<div class="letter" id="l188">e</div>
<div class="letter" id="l189">r</div>
</div>
The letter with the cursor before it also has the class cursor.
.cursor:before {
position: absolute;
width: 2px;
height: 30px;
background: var(--accent);
content: ' ';
}
Sometimes, when typing the first word of a line, the completed part of the word, which has the cursor after it, is bumped up to the line before it. This does not happen when the :before has no content. Please help me figure out why something with position: absolute is moving elements around. Thank you!
EDIT: Snippet
EDIT 2: The glitch only works with a certain combination of words, so if you cannot reproduce the glitch, please try again.
let dict = ['test', 'stack', 'overflow'];
let index = 0, words, wrong = 0, last;
let running;
let sec = 0, min = 0;
const text = document.querySelector('#text');
const st = document.querySelector('#sec');
const mt = document.querySelector('#min');
function genTest() {
words = "";
for (let i = 0; i < 100; i++) {
words += dict[randomRange(0, 2)];
if (i !== 99) words += " ";
}
let html = `<div class='word'>`;
let i = 0;
words.split('').forEach(l => {
if (l === ' ') html += `</div><div class="word">`;
if (i === 0) html += `<div class="letter curs-fade" id='l${i}'>${l}</div>`;
else html += `<div class="letter" id='l${i}'>${l}</div>`;
i++;
});
last = i;
html += '</div>'
text.innerHTML = html;
}
function initTest() {
running = false;
genTest();
st.classList = "";
mt.classList = "";
l(0).classList.add('cursor');
}
function start() {
running = true;
st.classList.add('txt-active');
setInterval(() => {
sec++;
if (sec >= 60) {
sec %= 60;
min++;
if (min === 1) {
mt.classList.add('txt-active');
}
}
mt.innerHTML = min.toString() + ':';
st.innerHTML = ((sec < 10) ? '0' : '') + sec.toString();
}, 1000);
}
document.addEventListener('keydown', (e) => {
let key = e.key;
const cl = l(index);
if (wrong > 0 && key === 'Backspace') {
wrong--;
w(wrong).remove();
return;
}
if (key.match(/^[a-zA-Z"'\s]+$/) && key.length === 1) {
if (index === 0 && !running) {
start();
}
if (cl.innerHTML === key.toLowerCase() && wrong === 0) {
cl.classList.add('correct');
index++;
} else if (key !== ' ') {
let w = document.createElement('DIV');
w.classList.add('letter');
w.classList.add('incorrect');
w.id = "w" + wrong;
w.innerHTML = key;
wrong++;
if (index > 0) l(index - 1).appendChild(w);
else {
let n = l(index);
n.parentNode.insertBefore(w, n);
}
}
cl.classList.remove('cursor');
l(index).classList.add('cursor');
}
});
function l(index) {
return document.getElementById('l' + index);
}
function w(index) {
return document.getElementById('w' + index);
}
function randomRange(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
initTest();
#import url('https://fonts.googleapis.com/css2?family=Roboto+Mono:ital,wght#0,100;0,200;0,300;0,400;0,500;0,600;0,700;1,100;1,200;1,300;1,400;1,500;1,600;1,700&display=swap');
* {
font-family: 'Roboto Mono', monospace;
}
body, html {
margin: 0;
width: 100%;
height: 100%;
overflow: hidden;
}
body {
background-color: #0f0f0f;
--accent: yellow;
--gray: #ababab;
--dark-gray: #8f8f8f;
user-select: none;
-moz-user-select: none;
-ms-user-select: none;
-webkit-user-select: none;
}
.header {
margin: 10px 150px;
}
.title {
font-size: 50px;
font-weight: 200;
color: white;
}
#text {
color: var(--gray);
margin: 20px 150px;
text-align: left;
}
.timer {
color: var(--dark-gray);
font-size: 50px;
font-weight: 300;
text-align: center;
margin: 100px 0 0;
}
.txt-active {
color: white;
transition: color .7s ease;
}
#min, #sec {
display: inline;
}
.word {
display: inline;
}
.letter {
display: inline;
font-weight: 200;
font-size: 24px;
}
.correct {
color: white;
}
.incorrect {
color: #d26f6f;
}
.cursor:before {
position: absolute;
width: 2px;
height: 30px;
background: var(--accent);
content: ' ';
}
.curs-fade:before {
animation: cursor-fade alternate-reverse .8s infinite;
}
#keyframes cursor-fade {
80% {opacity: 1}
0% {opacity: 0}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="styles/style.css">
<title>Typeracer++</title>
</head>
<body>
<div class="header">
<div class="title">typeracer++</div>
</div>
<div class="test">
<div class="timer"><div id="min">0:</div><div id="sec">00</div></div>
<div id="text"></div>
</div>
<script type="text/javascript" src="scripts/game.js"></script>
</body>
</html>
I have a game with a character that goes to a random position whenever you click on it. Also, I made it so the game automatically goes into full-screen. However, sometimes, the character goes way off-screen and (because there are no scroll bars in full-screen) you cant get to it. The code is below.
<!doctype html>
<html>
<head>
<link href='https://fonts.googleapis.com/css?family=Alfa Slab One' rel='stylesheet'> <!-- add the font used -->
<script type="text/javascript">
function move() { //move the bird
const height = screen.height; //set the screen params
const width = screen.width;
const box = document.getElementById("bird"); //search for the bird
let randY = Math.floor((Math.random() * height) + 1); //randomise the coords
let randX = Math.floor((Math.random() * width) + 1);
box.style.transform = `translate(${randX}px, ${randY}px)`; //move the bird
addScore(); //add the score
}
</script>
<script type="text/javascript">
function getreqfullscreen(){ //full screen it. I cant really understand how it works
var root = document.documentElement
return root.requestFullscreen || root.webkitRequestFullscreen || root.mozRequestFullScreen || root.msRequestFullscreen
}
function startFullScreen() {
var pagebody = document.getElementById("main");
var globalreqfullscreen = getreqfullscreen();
document.addEventListener('click', function(e){
var target = e.target
globalreqfullscreen.call(pagebody)
}, false)
}
</script>
<script type="text/javascript">
var points = 0;
function addScore() { //add the score
var pointcount = document.getElementById("scoreCount"); //get the score counter
//var points = 45; --used for testing
points = points + 1; //increment the points
pointcount.innerText = "score: " + points;
//pointCounter.removeChild(pointCounter.childNodes[0]); --used for an older prototype
}
/**************************************/
function startCountdown() { //initiate the timer - starts when the <body> loads
startFullScreen(); //make it full screen
var time = 9999999999999999999999; //would be 60, but I made it infinite
setInterval(function() { //decrease every second
var timer = document.getElementById("Timer"); //get the timer
time = time - 1; //decrement the timer
timer.innerText = "time: " + time;
if(time == 0) { //if you finished
var continuE = prompt("Would you like to restart? (type Y for yes and N for no (case sensitive)).");
if(continuE == "Y") {
window.location.reload();
} else {
history.go(-1);
}
}
},1000);
}
</script>
<style>
html {
cursor: crosshair;
background-color: #00b0e6;
user-select: none;
}
#bird {
position: absolute;
background-color: #ffffff;
cursor: crosshair;
transition: all 1s ease-in-out;
}
#bird:hover {
invert: 0 0 12px #ff0000;
}
/*
span {
height:10px;ss
width:200px;
border:5px double red;
color:#ff00ff;
background-color:#00ffff;
}
*/
p {
color: #ff00ff;
background-color: #000000;
border: 5px double red;
height: 60px;
width: 85px;
margin: 10px;
font-family: "Times New Roman";
}
.restartButton {
border-radius: 999px;
background-color: #ff00ff;
color: #00fffff;
border: 10px double blue;
transition: all 1s ease-out;
margin-left: 50%;
margin-right: 50%;
position: relative;
cursor: help;
}
.restartButton:hover {
border-radius: 999px;
background-color: #ffffff;
color: #4500fff;
border: 10px solid red;
}
#scoreCount {
color: #aff823;
position: fixed;
top: 0;
width: 10px;
height: 10px;
}
#Timer {
color: #aff823;
position: fixed;
top: 0;
left: 200px;
width: 10px;
height: 10px;
}
span {
font-family: Alfa Slab One;
}
#main {
background-color: #00b0e6;
}
</style>
</head>
<body onload="startCountdown()" id="body">
<div id="main">
<div id="pointCounter"><span id="scoreCount"></span><span id="Timer"></span></div>
<input type="button" value="RESTART" onclick="window.location.reload();" class="restartButton"/>
<img src="https://art.pixilart.com/81a784782ea5697.png" alt="" height="50px" width="50px" id="bird" onclick="move();">
</div>
<noscript>
YOU DO NOT HAVE JAVASCRIPT ENABLED. PLEASE ENABLE JAVASCRIPT ELSE THIS WEB PAGE WILL NOT WORK.
</noscript>
</body>
</html>
Because of how stack overflow works, it doesn't go into full-screen.
P.S. I have made it infinite time, it's meant to only be 60 seconds.
Here is a beautiful Number Ticker. the whole day I was wondering and trying to modify the code to make it as I want but no success till now!
if you work with numbers with two or more digits then the code creates separate black squares to hold each digit ( run code snippet to have a look ), but I want only a single square as the container to hold multiple digit numbers. So if we have a two-digit number like 10 the Number Ticker should be something like this:
And the next move should look like :
I don't want those parallel animations that move two digits like this (Only the single animation is required not both):
Here is the code:
let counters = document.getElementsByClassName('number-ticker');
let defaultDigitNode = document.createElement('div');
defaultDigitNode.classList.add('digit');
for (let i = 0; i < 11; i++) {
defaultDigitNode.innerHTML += i + '<br>';
}
[].forEach.call(counters, function(counter) {
let currentValue = 10;
let digits = [];
generateDigits(currentValue.toString().length);
setValue(currentValue);
setTimeout(function() {
setValue(8);
}, 2000);
setTimeout(function() {
setValue(7);
}, 5000);
function setValue(number) {
let s = number.toString().split('').reverse().join('');
let l = s.length;
if (l > digits.length) {
generateDigits(l - digits.length);
}
for (let i = 0; i < digits.length; i++) {
setDigit(i, s[i] || 0);
}
}
function setDigit(digitIndex, number) {
digits[digitIndex].style.marginTop = '-' + number + 'em';
}
function generateDigits(amount) {
for (let i = 0; i < amount; i++) {
let d = defaultDigitNode.cloneNode(true);
counter.appendChild(d);
digits.unshift(d);
}
}
});
:root {
background-color: #555;
color: white;
font-size: 25vh;
font-family: Roboto Light;
}
body,
html {
margin: 0;
height: 100%;
}
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100%;
}
.number-ticker {
overflow: hidden;
height: 1em;
background-color: #333;
box-shadow: 0 0 0.05em black inset;
}
.number-ticker .digit {
float: left;
line-height: 1;
transition: margin-top 1.75s ease;
border-right: 1px solid #555;
padding: 0 0.075em;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Number Ticker</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="number-ticker.css">
</head>
<body>
<div class="container">
<div class="number-ticker" data-value="0"></div>
</div>
<script src="number-ticker.js"></script>
</body>
</html>
Your css has this
.number-ticker .digit {
float: left;
line-height: 1;
transition: margin-top 1.75s ease;
border-right: 1px solid #555;
padding: 0 0.075em;
}
You need to change it to this
.number-ticker .digit {
float: left;
line-height: 1;
transition: margin-top 1.75s ease;
padding: 0 0.075em;
text-align: center;
}
If you remove border-right: 1px solid #555 you will have it look like 1 box.
Also I added text-align: center to center the numbers.
Hope this solves your problem :)
I think the main issue in your code is the digits variable. It creates an array of HTML elements that holds two blocks.
Also, for this line:
let s = number.toString().split('').reverse().join('');
Why do you need to convert number to a string. You can just pass it as is. Once you add to a string using + it will be converted.
I made few changes to your code and commented out the non-relevant part. Please see below:
let counters = document.getElementsByClassName('number-ticker');
let defaultDigitNode = document.createElement('div');
defaultDigitNode.classList.add('digit');
for (let i = 0; i < 11; i++) {
defaultDigitNode.innerHTML += i + '<br>';
}
[].forEach.call(counters, function(counter) {
// let currentValue = 10;
// let digits = [];
let currentValue = counter.getAttribute("data-value");
let digit = null;
generateDigits(currentValue.toString().length);
setValue(currentValue);
setTimeout(function() {
setValue(8);
}, 2000);
setTimeout(function() {
setValue(7);
}, 5000);
setTimeout(function() {
setValue(10);
}, 8000);
function setValue(number) {
// let s = number.toString().split('').reverse().join('');
// let l = s.length;
/*if (l > digits.length) {
generateDigits(l - digits.length);
}*/
/*for (let i = 0; i < digits.length; i++) {
setDigit(i, s[i] || 0);
}*/
digit.style.marginTop = '-' + number + 'em';
}
/*function setDigit(digitIndex, number) {
console.log(number);
digits[digitIndex].style.marginTop = '-' + number + 'em';
}*/
function generateDigits(amount) {
// console.log("generat", amount);
// for (let i = 0; i < amount; i++) {
let d = defaultDigitNode.cloneNode(true);
digit = counter.appendChild(d);
// digits.unshift(d);
// }
}
});
:root {
background-color: #555;
color: white;
font-size: 25vh;
font-family: Roboto Light;
}
body,
html {
margin: 0;
height: 100%;
}
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100%;
}
.number-ticker {
overflow: hidden;
height: 1em;
background-color: #333;
box-shadow: 0 0 0.05em black inset;
}
.number-ticker .digit {
float: left;
line-height: 1;
transition: margin-top 1.75s ease;
border-right: 1px solid #555;
padding: 0 0.075em;
text-align: center;
}
<div class="container">
<div class="number-ticker" data-value="0"></div>
</div>
Your final JS could be like this:
let counters = document.getElementsByClassName('number-ticker');
let defaultDigitNode = document.createElement('div');
defaultDigitNode.classList.add('digit');
for (let i = 0; i < 11; i++) {
defaultDigitNode.innerHTML += i + '<br>';
}
[].forEach.call(counters, function(counter) {
let currentValue = counter.getAttribute("data-value");
let d = defaultDigitNode.cloneNode(true);
let digit = counter.appendChild(d);
setValue(currentValue);
function setValue(number) {
digit.style.marginTop = '-' + number + 'em';
}
});
I have written a program in javascript that matches the images which are randomly shuffled in a 4x4 grid. I have read that for flipping the images, you need to have a front image and a back image. I have declared the "back" images for my program in an Array inside of Javascript and have the common "front" image declared in the div holding those images. Now, I am unable to target the front or back images in my program for applying all the css3 transformation code as they are declared in the Javascript. Hence, I need help in suggesting me a way to achieve flipping in my program. Here is my code:
HTML:
<div class="container">
<div class="page-header">
Match The Flag!
</div>
<div id="clicks"> </div>
<div id="memory_board" onClick="Click()"></div>
<script>newBoard();</script>
<!-- <button onclick=" return newBoard();"> Reset </button> -->
<div class="refresh">
<img src="images/refresh.png" alt="refresh" onclick="return location.reload();">
</div>
</div>
Javscript
<script>
var memory_array = ['A','A','B','B','C','C','D','D','E','E','F','F','G','G','H','H'];
var memory_values = [];
var memory_tile_ids = [];
var tiles_flipped = 0;
Array.prototype.memory_tile_shuffle = function() /* Shuffle Function to Randomly Position the Cards */
{
var i = this.length, j, temp; /* this.length keyword will automatically take the length of the parameter passed to the parent function i.e array of cards */
while(i--){
j = Math.floor(Math.random() * (i+1));
temp = this[j];
this[j] = this[i];
this[i] = temp;
}
}
function newBoard()
{
var i = 0;
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;
localStorage.setItem("score1", clicks);
}
function memoryFlipTile(tile, val)
{
if(tile.innerHTML == "" && memory_values.length < 2)
{
tile.style.background = '#FFF';
tile.innerHTML = '<img src="' + val + '.png"/>'; /* Adding .png format after our image array */
if(memory_values.length == 0) /* For First Click on the image */
{
memory_values.push(val);
memory_tile_ids.push(tile.id);
}
else if(memory_values.length == 1) /* For Second Click on the other image */
{
memory_values.push(val);
memory_tile_ids.push(tile.id);
console.log(memory_values[0]+" "+memory_values[1]);
if(memory_values[0] == memory_values[1])
{
document.getElementById(memory_tile_ids[0]).style.backgroundColor = "lightgreen";
document.getElementById(memory_tile_ids[1]).style.backgroundColor = "lightgreen";
tiles_flipped += 2;
memory_values = []; /* Clear arrays */
memory_tile_ids = []; /* Clear arrays */
if(tiles_flipped == memory_array.length) /* Check to see if all cards are flipped back */
{
var score = Click();
score--;
/*console.log("Score: "+score);/*
/*alert("All Tiles Flipped. Your Score: "+score);*/
document.getElementById('memory_board').innerHTML = "";
/*newBoard();*/ // Don't Remove
/*var i = 0;
location.reload();*/
}
}
else /* If the images don't match, then flip the two flipped images back */
{
function flipBack()
{
var tile_1 = document.getElementById(memory_tile_ids[0]);
var tile_2 = document.getElementById(memory_tile_ids[1]);
tile_1.style.background = 'url(images/card.png) no-repeat';
tile_1.style.backgroundSize = '100% 100%';
tile_1.innerHTML = "";
tile_2.style.background = 'url(images/card.png) no-repeat';
tile_2.style.backgroundSize = '100% 100%';
tile_2.innerHTML = "";
memory_values = []; /* Clear arrays */
memory_tile_ids = []; /* Clear arrays */
}
setTimeout(flipBack, 700);
}
}
}
}
var clicks = 0;
var previous_scores = localStorage.getItem("old-score");
console.log(previous_scores);
function Click()
{
if(tiles_flipped == memory_array.length)
{
document.getElementById("clicks").innerHTML = "New Score: "+clicks+"<br>"+"Old Score: "+previous_scores;
localStorage.setItem("old-score", clicks);
/*window.location.href = "score.html";*/
}
else
{
clicks += 1;
document.getElementById("clicks").innerHTML = "Clicks: "+clicks;
return clicks;
}
}
</script>
CSS
#memory_board
{
width: 760px;
height: 660px;
padding: 40px;
margin: 0px auto;
}
#memory_board > div
{
background-color: lightblue;
background: url('images/card.png') no-repeat;
background-size: 100% 100%;
width: 130px;
height: 120px;
float: left;
margin: 10px;
padding: 20px;
font-size: 64px;
cursor: pointer;
text-align: center;
border-radius: 5px;
}
#tile_0 img, #tile_1 img, #tile_2 img, #tile_3 img, #tile_4 img, #tile_5 img, #tile_6 img, #tile_7 img, #tile_8 img, #tile_9 img, #tile_10 img, #tile_11 img, #tile_12 img, #tile_13 img, #tile_14 img, #tile_15 img
{
width: 100px;
margin-top: 30px;
}
Here is an example of flipping an image from a front image to a back image.
You should be able to adapt this example so that it works within your setup.
.container {
position: relative;
width: 100px;
height: 130px;
perspective: 800px;
}
.card {
position: absolute;
width: 100%;
height: 100%;
transform-style: preserve-3d;
transition: transform 1s;
}
.card div {
display: block;
position: absolute;
top: 0;
left: 0;
margin: 0;
width: 100%;
height: 100%;
line-height: 130px;
text-align: center;
font-weight: bold;
font-size: 90px;
color: rgb(255, 255, 255);
text-shadow: 4px 4px 4px rgba(0, 0, 0, 0.4);
backface-visibility: hidden;
}
.card .front {
background: url('http://placekitten.com/400/520') 0 0 / 100px 130px no-repeat;
}
.card .back {
background: url('http://placekitten.com/1600/2080') 0 0 / 100px 130px no-repeat;
transform: rotateY( 180deg );
}
.card:hover {
transform: rotateY( 180deg );
}
<section class="container">
<div class="card">
<div class="front"></div>
<div class="back"></div>
</div>
</section>
Credit: The example above is modified from the markup and styling provided in the tutorial at:
https://desandro.github.io/3dtransforms/docs/card-flip.html