This question already has answers here:
How to compare arrays in JavaScript?
(61 answers)
How to check if somebody won in a tic tac toe game in javascript?
(2 answers)
Closed 11 days ago.
I'm trying to make a tic-tac-toe game in JavaScript. I'm currently trying to compare an array in an object to a possible win combination and I'm unsure where I'm going wrong.
I'm planning to compare gameboard to an array of arrays that contain possible win combinations.
const tiles = document.querySelectorAll('.tile');
const _gameBoardObj = {
gameboard: ["", "", "", "", "", "", "", "", ""],
};
function renderBoard() {
for (i = 0; i < _gameBoardObj.gameboard.length; i++) {
for (i = 0, max = tiles.length; i < max; i++) {
if (_gameBoardObj.gameboard[i] === 0) {
tiles[i].textContent = "O";
} else if (_gameBoardObj.gameboard[i] === 1) {
tiles[i].textContent = "X";
} else {
tiles[i].textContent = "";
}
}
}
}
function chooseTile() {
tiles.forEach((tile, index) => {
tile.addEventListener('click', () => {
if (_gameBoardObj.gameboard[index] == "") {
_gameBoardObj.gameboard[index] = 1;
renderBoard();
checkGameOver();
}
})
})
}
function checkGameOver() {
if (_gameBoardObj.gameboard == [1, 1, 1, "", "", "", "", "", ""]) {
alert("Game Over")
}
}
chooseTile()
.board {
display: grid;
grid-template-columns: auto auto auto;
padding: 10px;
width: 300px;
height: 300px;
}
.tile {
background-color: rgba(255, 255, 255, 0.8);
border: 1px solid rgba(0, 0, 0, 0.8);
font-size: 30px;
text-align: center;
}
<div class="board">
<div class="tile one" id="0">
</div>
<div class="tile two" id="1">
</div>
<div class="tile three" id="2">
</div>
<div class="tile four" id="3">
</div>
<div class="tile five" id="4">
</div>
<div class="tile six" id="5">
</div>
<div class="tile seven" id="6">
</div>
<div class="tile eight" id="7">
</div>
<div class="tile nine" id="8">
</div>
</div>
Related
I struggle with a functionnality I want to implement to my exercice : when we drop an element on something that already has an element, I want this to switch it with the other one.
You don't have the pictures, but the main thing is working.
If you have any idea of how I could do this (or where to start working).
const fills = document.querySelectorAll('.fill');
const empties = document.querySelectorAll('.empty');
var actualFill = null;
var scrollSpaceTop = document.getElementById("scrollSpaceTop");
scrollSpaceTop.remove();
var scrollSpaceBottom = document.getElementById("scrollSpaceBottom");
scrollSpaceBottom.remove();
var scrolls = document.getElementById("scrolls");
const questions = document.getElementById("questions");
var elements = [];
var elemNumb = 24;
for(let i = 1; i < elemNumb; i++)
{
window['ques'+i] = document.getElementById("ques"+i);
elements.push(window['ques'+i]);
}
ShuffleArray(elements);
for(element of elements)
{
element.remove();
questions.appendChild(element);
}
for(const fill of fills){
fill.addEventListener('dragstart', dragStart);
fill.addEventListener('dragend', dragEnd);
}
for(const empty of empties){
empty.addEventListener('dragover', dragOver);
empty.addEventListener('dragenter', dragEnter);
empty.addEventListener('dragleave', dragLeave);
empty.addEventListener('drop', dragDrop);
}
function dragStart() {
this.className += ' hold';
setTimeout(() => (this.className ='invisible'), 0);
actualFill = this;
scrolls.appendChild(scrollSpaceTop);
scrolls.appendChild(scrollSpaceBottom);
}
function dragEnd() {
this.className = 'fill';
scrollSpaceTop.remove();
scrollSpaceBottom.remove();
}
function dragOver(e){
e.preventDefault();
}
function dragEnter(e){
e.preventDefault();
this.className += ' hovered';
}
function dragLeave() {
this.className = 'empty';
}
function dragDrop() {
if (this.hasChildNodes())
{
var childs = this.childNodes;
for(var child of childs)
{
if(child.nodeName == "DIV")
{
this.className = 'empty';
console.log('not empty');
return;
}
}
this.className = 'empty';
this.append(actualFill);
}
else
{
this.className = 'empty';
this.append(actualFill);
}
}
function Validate()
{
var score = 0;
//PLEIN
var q1 = document.getElementById("q1");
if (q1.hasChildNodes())
{
cq1 = q1.childNodes[0];
if(cq1.id == "plein")
{
q1.parentElement.style.borderColor = "lightgreen";
++score;
}
else
{
q1.parentElement.style.borderColor = "Crimson";
}
}
else
{
q1.parentElement.style.borderColor = "Crimson";
}
//BON
var q2 = document.getElementById("q2");
if (q2.hasChildNodes())
{
cq2 = q2.childNodes[0];
if(cq2.id == "bon")
{
q2.parentElement.style.borderColor = "lightgreen";
++score;
}
else
{
q2.parentElement.style.borderColor = "Crimson";
}
}
else
{
q2.parentElement.style.borderColor = "Crimson";
}
//SALE
var q3 = document.getElementById("q3");
if (q3.hasChildNodes())
{
cq3 = q3.childNodes[0];
if(cq3.id == "sale")
{
q3.parentElement.style.borderColor = "lightgreen";
++score;
}
else
{
q3.parentElement.style.borderColor = "Crimson";
}
}
else
{
q3.parentElement.style.borderColor = "Crimson";
}
//SUCRE
var q4 = document.getElementById("q4");
if (q4.hasChildNodes())
{
cq4 = q4.childNodes[0];
if(cq4.id == "sucre")
{
q4.parentElement.style.borderColor = "lightgreen";
++score;
}
else
{
q4.parentElement.style.borderColor = "Crimson";
}
}
else
{
q4.parentElement.style.borderColor = "Crimson";
}
//VIDE
var q5 = document.getElementById("q5");
if (q5.hasChildNodes())
{
cq5 = q5.childNodes[0];
if(cq5.id == "vide")
{
q5.parentElement.style.borderColor = "lightgreen";
++score;
}
else
{
q5.parentElement.style.borderColor = "Crimson";
}
}
else
{
q5.parentElement.style.borderColor = "Crimson";
}
//MAUVAIS
var q6 = document.getElementById("q6");
if (q6.hasChildNodes())
{
cq6 = q6.childNodes[0];
if(cq6.id == "mauvais")
{
q6.parentElement.style.borderColor = "lightgreen";
++score;
}
else
{
q6.parentElement.style.borderColor = "Crimson";
}
}
else
{
q6.parentElement.style.borderColor = "Crimson";
}
//l'assiette
var q7 = document.getElementById("q7");
if (q7.hasChildNodes())
{
cq7 = q7.childNodes[0];
if(cq7.id == "assiette")
{
q7.parentElement.style.borderColor = "lightgreen";
++score;
}
else
{
q7.parentElement.style.borderColor = "Crimson";
}
}
else
{
q7.parentElement.style.borderColor = "Crimson";
}
//tasse
var q8 = document.getElementById("q8");
if (q8.hasChildNodes())
{
cq8 = q8.childNodes[0];
if(cq8.id == "tasse")
{
q8.parentElement.style.borderColor = "lightgreen";
++score;
}
else
{
q8.parentElement.style.borderColor = "Crimson";
}
}
else
{
q8.parentElement.style.borderColor = "Crimson";
}
//verre
var q9 = document.getElementById("q9");
if (q9.hasChildNodes())
{
cq9 = q9.childNodes[0];
if(cq9.id == "verre")
{
q9.parentElement.style.borderColor = "lightgreen";
++score;
}
else
{
q9.parentElement.style.borderColor = "Crimson";
}
}
else
{
q9.parentElement.style.borderColor = "Crimson";
}
//couteau
var q10 = document.getElementById("q10");
if (q10.hasChildNodes())
{
cq10 = q10.childNodes[0];
if(cq10.id == "couteau")
{
q10.parentElement.style.borderColor = "lightgreen";
++score;
}
else
{
q10.parentElement.style.borderColor = "Crimson";
}
}
else
{
q10.parentElement.style.borderColor = "Crimson";
}
//fourchette
var q11 = document.getElementById("q11");
if (q11.hasChildNodes())
{
cq11 = q11.childNodes[0];
if(cq11.id == "fourchette")
{
q11.parentElement.style.borderColor = "lightgreen";
++score;
}
else
{
q11.parentElement.style.borderColor = "Crimson";
}
}
else
{
q11.parentElement.style.borderColor = "Crimson";
}
//cuillère
var q12 = document.getElementById("q12");
if (q12.hasChildNodes())
{
cq12 = q12.childNodes[0];
if(cq12.id == "cuillere")
{
q12.parentElement.style.borderColor = "lightgreen";
++score;
}
else
{
q12.parentElement.style.borderColor = "Crimson";
}
}
else
{
q12.parentElement.style.borderColor = "Crimson";
}
//viande
var q13 = document.getElementById("q13");
if (q13.hasChildNodes())
{
cq13 = q13.childNodes[0];
if(cq13.id == "viande")
{
q13.parentElement.style.borderColor = "lightgreen";
++score;
}
else
{
q13.parentElement.style.borderColor = "Crimson";
}
}
else
{
q13.parentElement.style.borderColor = "Crimson";
}
//poisson
var q14 = document.getElementById("q14");
if (q14.hasChildNodes())
{
cq14 = q14.childNodes[0];
if(cq14.id == "poisson")
{
q14.parentElement.style.borderColor = "lightgreen";
++score;
}
else
{
q14.parentElement.style.borderColor = "Crimson";
}
}
else
{
q14.parentElement.style.borderColor = "Crimson";
}
//fruits
var q15 = document.getElementById("q15");
if (q15.hasChildNodes())
{
cq15 = q15.childNodes[0];
if(cq15.id == "fruits")
{
q15.parentElement.style.borderColor = "lightgreen";
++score;
}
else
{
q15.parentElement.style.borderColor = "Crimson";
}
}
else
{
q15.parentElement.style.borderColor = "Crimson";
}
//legumes
var q16= document.getElementById("q16");
if (q16.hasChildNodes())
{
cq16 = q16.childNodes[0];
if(cq16.id == "legumes")
{
q16.parentElement.style.borderColor = "lightgreen";
++score;
}
else
{
q16.parentElement.style.borderColor = "Crimson";
}
}
else
{
q16.parentElement.style.borderColor = "Crimson";
}
//pain
var q17 = document.getElementById("q17");
if (q17.hasChildNodes())
{
cq17 = q17.childNodes[0];
if(cq17.id == "pain")
{
q17.parentElement.style.borderColor = "lightgreen";
++score;
}
else
{
q17.parentElement.style.borderColor = "Crimson";
}
}
else
{
q17.parentElement.style.borderColor = "Crimson";
}
//eau
var q18 = document.getElementById("q18");
if (q18.hasChildNodes())
{
cq18 = q18.childNodes[0];
if(cq18.id == "eau")
{
q18.parentElement.style.borderColor = "lightgreen";
++score;
}
else
{
q18.parentElement.style.borderColor = "Crimson";
}
}
else
{
q18.parentElement.style.borderColor = "Crimson";
}
//lait
var q19 = document.getElementById("q19");
if (q19.hasChildNodes())
{
cq19 = q19.childNodes[0];
if(cq19.id == "lait")
{
q19.parentElement.style.borderColor = "lightgreen";
++score;
}
else
{
q19.parentElement.style.borderColor = "Crimson";
}
}
else
{
q19.parentElement.style.borderColor = "Crimson";
}
//aimer
var q20 = document.getElementById("q20");
if (q20.hasChildNodes())
{
cq20 = q20.childNodes[0];
if(cq20.id == "aimer")
{
q20.parentElement.style.borderColor = "lightgreen";
++score;
}
else
{
q20.parentElement.style.borderColor = "Crimson";
}
}
else
{
q20.parentElement.style.borderColor = "Crimson";
}
//détester
var q21 = document.getElementById("q21");
if (q21.hasChildNodes())
{
cq21 = q21.childNodes[0];
if(cq21.id == "detester")
{
q21.parentElement.style.borderColor = "lightgreen";
++score;
}
else
{
q21.parentElement.style.borderColor = "Crimson";
}
}
else
{
q21.parentElement.style.borderColor = "Crimson";
}
//boire
var q22 = document.getElementById("q22");
if (q22.hasChildNodes())
{
cq22 = q22.childNodes[0];
if(cq22.id == "boire")
{
q22.parentElement.style.borderColor = "lightgreen";
++score;
}
else
{
q22.parentElement.style.borderColor = "Crimson";
}
}
else
{
q22.parentElement.style.borderColor = "Crimson";
}
//manger
var q23 = document.getElementById("q23");
if (q23.hasChildNodes())
{
cq23 = q23.childNodes[0];
if(cq23.id == "manger")
{
q23.parentElement.style.borderColor = "lightgreen";
++score;
}
else
{
q23.parentElement.style.borderColor = "Crimson";
}
}
else
{
q23.parentElement.style.borderColor = "Crimson";
}
alert("Ton Score est de : " + score +"/23");
}
function ShuffleArray(myArr)
{
var l = myArr.length, temp, index;
while (l > 0) {
index = Math.floor(Math.random() * l);
l--;
temp = myArr[l];
myArr[l] = myArr[index];
myArr[index] = temp;
}
return myArr;
}
function Offset(el)
{
var rect = el.getBoundingClientRect(),
scrollLeft = window.pageXOffset || document.documentElement.scrollLeft,
scrollTop = window.pageYOffset || document.documentElement.scrollTop;
return { top: rect.top + scrollTop, left: rect.left + scrollLeft }
}
function ScrollBottom(){
window.scrollBy({ top: 200, left: 0, behavior: 'smooth'});
}
function ScrollTop(){
window.scrollBy({ top: -200, left: 0, behavior: 'smooth'});
}
body{
background: darksalmon;
}
.fill{
background: lightgrey;
position: relative;
height: 4.5vh;
width: 14.5vh;
margin: 0.5vh;
cursor: pointer;
text-align: center;
border: 0.3vh grey dashed ;
}
.empty{
display: inline-block;
height: 6vh;
width: 16vh;
margin: 1vh;
border : 0.3vh salmon solid;
background-color: rgb(245, 245, 245);
vertical-align: bottom;
}
.reponse{
}
.reponses{
position: relative;
background-color: rgb(245, 245, 245);
text-align: center;
max-width: 190vh;
margin: 0 auto;
border-radius: 3vh;
top:2vh;
}
.hold{
border : solid grey 0.4vh;
opacity: 1;
}
.hovered{
background: #f4f4f4;
border-style: dashed;
}
.invisible{
display: none;
}
.questions{
position: relative;
margin: 0 auto;
background-color: white;
top: 5vh;
text-align: center;
max-width: 190vh;
border-radius: 3vh;
}
.question{
margin: 4vh 2vh;
padding: 2vh;
background-color: darkgrey;
border: black 1vh solid;
text-align: center;
max-width: 25vh;
max-height: 25vh;
display: inline-block;
}
.text{
position: absolute;
height: 4vh;
width: 14vh;
margin: 0.6vh 0.25vh;
font-size: 2.5vh;
user-select: none;
}
.imageContainer{
display: inline-block;
width: 21vh;
height: 21vh;
border: grey 0.3vh dashed;
background-color: lightgrey;
text-align: center;
}
.image{
display: block;
max-width: 20vh;
max-height: 20vh;
margin: auto auto;
position: relative;
top: 50%;
transform: translate(0, -50%);
}
.btn{
position: relative;
display: block;
width: 20vh;
height: 5vh;
top: 6vh;
left: 50%;
transform: translate(-50%, 0%);
font-size: 2vh;
border: 0.3vh black solid;
}
.mainTitle{
font-size: 4vh;
text-align: center;
background: rgb(245, 245, 245);
padding: 1vh 1vh;
margin: auto auto;
border: 0.3vh dashed darkgrey;
max-width: 80vh;
}
.btnContainer{
top:1vh;
position: relative;
height: 13vh;
}
.menuLink{
display: inline-block;
position: relative;
font-size: 2vw;
text-decoration:none;
color: black;
margin:auto auto;
top: 50%;
transform: translate(0, -50%);
}
.menuLinkContainer{
display: inline-block;
position: fixed;
width: 7vw;
height: 3vw;
background-color: rgb(245, 245, 245);
border: 0.3vh solid darkgrey;
top:1vh;
left:1vh;
text-align: center;
z-index: 1;
}
.scrollSpaceBottom{
display: inline-block;
position: fixed;
width: 100vw;
height: 15vh;
top:85vh;
}
.scrollSpaceTop{
display: inline-block;
position: fixed;
width: 100vw;
height: 15vh;
bottom: 85vh;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css" />
<title>Associe les mots et les images</title>
</head>
<body>
<div class="menuLinkContainer">Menu</div>
<h1 class="mainTitle">Associe les mots et les images</h1>
<div class="reponses">
<div class="empty reponse">
<div class="fill" draggable="true" id = "sale"><div class="text">salé</div></div>
</div>
<div class="empty reponse">
<div class="fill" draggable="true" id = "plein"><div class="text">plein</div></div>
</div>
<div class="empty reponse">
<div class="fill" draggable="true" id = "sucre"><div class="text">sucré</div></div>
</div>
<div class="empty reponse">
<div class="fill" draggable="true" id = "bon"><div class="text">bon</div></div>
</div>
<div class="empty reponse">
<div class="fill" draggable="true" id = "vide"><div class="text">vide</div></div>
</div>
<div class="empty reponse">
<div class="fill" draggable="true" id = "mauvais"><div class="text">mauvais</div></div>
</div>
<div class="empty reponse">
<div class="fill" draggable="true" id = "assiette"><div class="text">l'assiette</div></div>
</div>
<div class="empty reponse">
<div class="fill" draggable="true" id = "tasse"><div class="text">la tasse</div></div>
</div>
<div class="empty reponse">
<div class="fill" draggable="true" id = "verre"><div class="text">le verre</div></div>
</div>
<div class="empty reponse">
<div class="fill" draggable="true" id = "couteau"><div class="text">le couteau</div></div>
</div>
<div class="empty reponse">
<div class="fill" draggable="true" id = "fourchette"><div class="text">la fourchette</div></div>
</div>
<div class="empty reponse">
<div class="fill" draggable="true" id = "cuillere"><div class="text">la cuillère</div></div>
</div>
<div class="empty reponse">
<div class="fill" draggable="true" id = "viande"><div class="text">la viande</div></div>
</div>
<div class="empty reponse">
<div class="fill" draggable="true" id = "poisson"><div class="text">le poisson</div></div>
</div>
<div class="empty reponse">
<div class="fill" draggable="true" id = "fruits"><div class="text">les fruits</div></div>
</div>
<div class="empty reponse">
<div class="fill" draggable="true" id = "legumes"><div class="text">les légumes</div></div>
</div>
<div class="empty reponse">
<div class="fill" draggable="true" id = "pain"><div class="text">le pain</div></div>
</div>
<div class="empty reponse">
<div class="fill" draggable="true" id = "eau"><div class="text">l'eau</div></div>
</div>
<div class="empty reponse">
<div class="fill" draggable="true" id = "lait"><div class="text">le lait</div></div>
</div>
<div class="empty reponse">
<div class="fill" draggable="true" id = "aimer"><div class="text">aimer</div></div>
</div>
<div class="empty reponse">
<div class="fill" draggable="true" id = "detester"><div class="text">détester</div></div>
</div>
<div class="empty reponse">
<div class="fill" draggable="true" id = "boire"><div class="text">boire</div></div>
</div>
<div class="empty reponse">
<div class="fill" draggable="true" id = "manger"><div class="text">manger</div></div>
</div>
</div>
<div class="questions" id="questions">
<div class="question" id="ques1">
<div class="imageContainer"><img src="./img/plein.png" class="image"></div>
<div class="empty" id="q1"></div>
</div>
<div class="question" id="ques2">
<div class="imageContainer"><img src="./img/bon.png" class="image"></div>
<div class="empty" id="q2"></div>
</div>
<div class="question" id="ques3">
<div class="imageContainer"><img src="./img/sale.png" class="image"></div>
<div class="empty" id="q3"></div>
</div>
<div class="question" id="ques4">
<div class="imageContainer"><img src="./img/sucre.png" class="image"></div>
<div class="empty" id="q4"></div>
</div>
<div class="question" id="ques5">
<div class="imageContainer"><img src="./img/vide.png" class="image"></div>
<div class="empty" id="q5"></div>
</div>
<div class="question" id="ques6">
<div class="imageContainer"><img src="./img/mauvais.png" class="image"></div>
<div class="empty" id="q6"></div>
</div>
<div class="question" id="ques7">
<div class="imageContainer"><img src="./img/assiette.png" class="image"></div>
<div class="empty" id="q7"></div>
</div>
<div class="question" id="ques8">
<div class="imageContainer"><img src="./img/tasse.png" class="image"></div>
<div class="empty" id="q8"></div>
</div>
<div class="question" id="ques9">
<div class="imageContainer"><img src="./img/verre.png" class="image"></div>
<div class="empty" id="q9"></div>
</div>
<div class="question" id="ques10">
<div class="imageContainer"><img src="./img/couteau.png" class="image"></div>
<div class="empty" id="q10"></div>
</div>
<div class="question" id="ques11">
<div class="imageContainer"><img src="./img/fourchette.png" class="image"></div>
<div class="empty" id="q11"></div>
</div>
<div class="question" id="ques12">
<div class="imageContainer"><img src="./img/cuillere.png" class="image"></div>
<div class="empty" id="q12"></div>
</div>
<div class="question" id="ques13">
<div class="imageContainer"><img src="./img/viande.png" class="image"></div>
<div class="empty" id="q13"></div>
</div>
<div class="question" id="ques14">
<div class="imageContainer"><img src="./img/poisson.png" class="image"></div>
<div class="empty" id="q14"></div>
</div>
<div class="question" id="ques15">
<div class="imageContainer"><img src="./img/fruit.png" class="image"></div>
<div class="empty" id="q15"></div>
</div>
<div class="question" id="ques16">
<div class="imageContainer"><img src="./img/legume.png" class="image"></div>
<div class="empty" id="q16"></div>
</div>
<div class="question" id="ques17">
<div class="imageContainer"><img src="./img/pain.png" class="image"></div>
<div class="empty" id="q17"></div>
</div>
<div class="question" id="ques18">
<div class="imageContainer"><img src="./img/eau.png" class="image"></div>
<div class="empty" id="q18"></div>
</div>
<div class="question" id="ques19">
<div class="imageContainer"><img src="./img/lait.png" class="image"></div>
<div class="empty" id="q19"></div>
</div>
<div class="question" id="ques20">
<div class="imageContainer"><img src="./img/aimer.png" class="image"></div>
<div class="empty" id="q20"></div>
</div>
<div class="question" id="ques21">
<div class="imageContainer"><img src="./img/detester.png" class="image"></div>
<div class="empty" id="q21"></div>
</div>
<div class="question" id="ques22">
<div class="imageContainer"><img src="./img/boire.png" class="image"></div>
<div class="empty" id="q22"></div>
</div>
<div class="question" id="ques23">
<div class="imageContainer"><img src="./img/manger.png" class="image"></div>
<div class="empty" id="q23"></div>
</div>
</div>
<div id="scrolls">
<div class="scrollSpaceTop" id="scrollSpaceTop" ondragover="ScrollTop()"></div>
<div class="scrollSpaceBottom" id="scrollSpaceBottom" ondragover="ScrollBottom()"></div>
</div>
<div class="btnContainer"><input type="button" value="Valider les réponses" onclick="Validate()" class="btn"></div>
<script src="DragnDrop.js"></script>
</body>
</html>
One approach will be to set a data attribute to responses containers like:
<div data-child="salé" class="empty reponse">
<div class="fill" data-parent="salé" draggable="true" id = "sale"><div class="text">salé</div></div>
</div>
Each time you drop an element, you remove the existing one from the answers and reattach back in his possible responses, and attach the new one. This way you know where to attach the removed element back in his place using document selectors.
I've been at this for a while and can't seem to crack it. I'm a beginner learning to code and I've put myself to the test to build a concentration game. I'm having the following issues;
I only have 11 tiles instead of 16.
I don't have any matching colours
My colours are locking into place when they should only do that when matched with their pair.
I look forward to seeing if someone more advanced can assist.
var resetButton = document.getElementById("reset-button");
var colors= ["square-1" - "square-9"];
for (var i= 0; i < 10; i++){
colors.push("square-" + i);
}
function GameSquare (el, color) {
this.el= el;
this.isOpen = false;
this.isLocked= false;
this.el.addEventListener("click", this, false);
this.setColor(colors);
}
GameSquare.prototype.handleEvent = function(e) {
switch (e.type) {
case "click":
if (this.isOpen || this.isLocked) {
return;
}
this.isOpen = true;
this.el.classList.add('flip');
checkGame(this);
}
}
GameSquare.prototype.reset= function() {
this.isOpen= false;
this.isLocked= false;
this.el.classList.remove('flip');
}
GameSquare.prototype.lock = function() {
this.isLocked = true;
this.isOpen = true;
}
GameSquare.prototype.setColor = function(color) {
this.el.children[0].children[1].classList.remove(this.color);
this.color = color;
this.el.children[0].children[1].classList.add(color);
}
var gameSquares = [];
function random(n) {
return Math.floor(Math.random() * n)
}
function getSomeColors() {
var colorscopy = colors.slice();
var randomColors = [];
for (var i = 0; i < 8; i++) {
var index = random(colorscopy.length);
randomColors.push(colorscopy.splice(index, 1)[0]);
}
return randomColors.concat(randomColors.slice());
}
function setupGame() {
var array = document.getElementsByClassName("game-square");
var randomColors = getSomeColors();
for (var i= 0; i < array.length; i++) {
var index= random(randomColors.length);
var color = randomColors.splice(index, 1)[0];
gameSquares.push(new GameSquare(array[i], color));
}
}
var firstSquare = null;
function checkGame (GameSquare) {
if(firstSquare === null) {
firstSquare = GameSquare;
return
}
if (firstSquare.color === GameSquare.color) {
firstSquare.lock();
GameSquare.lock();
} else {
var a = firstSquare;
var b = GameSquare;
setTimeout(function() {
a.reset();
b.reset();
}, 400);
}
firstSquare = null;
}
function randomizeColors(){
var randomColors= getSomeColors();
gameSquares.forEach(function(GameSquare){
var color = randomColors.splice(random(randomColors.length), 1)[0];
GameSquare.setColor(color);
});
}
function clearGame(){
gameSquares.forEach(function(GameSquare) {
gameSquares.reset();
});
setTimeout(function() {
randomizeColors();
}, 500);
}
setupGame()
* {
padding: 0;
margin: 0;
}
.game-square {
box-sizing: border-box;
border: 1px solid #000;
width: 100px;
height: 100px;
position: relative;
overflow: hidden;
}
.game-square > div {
width: 100%;
height: 200%;
position: absolute;
top: 0;
transition: 400ms;
}
.game-square > div > div {
height: 50%;
}
.game-square > div > div:first-child {
background-color: grey;
}
.flip > div {
top: -100%;
}
.square-0 {
background-color: aqua;
}
.square-1 {
background-color: bisque;
}
.square-2 {
background-color: blue;
}
.square-3 {
background-color: blueviolet;
}
.square-4 {
background-color: brown;
}
.square-5 {
background-color: cadetblue;
}
.square-6 {
background-color: chartreuse;
}
.square-7 {
background-color: chocolate;
}
.square-8 {
background-color: coral;
}
.square-9 {
background-color: teal;
}
#game {
width: 400px;
height: 400px;
display: flex;
flex-direction: row;
flex-wrap: wrap;
border: 1px solid red;
}
#game {
width: 400px;
height: 400px;
display: flex;
flex-direction: row;
flex-wrap: wrap;
}
#reset-button{
position: absolute;
top: 90px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Concentration Game</title>
<link href= "./styles.css" rel="stylesheet" type= "text/css">
</head>
<body>
<div class="container">
<div id="game">
<div class= "game-square">
<div>
<div></div>
<div class= "square-0"></div>
</div>
</div>
<div class= "game-square">
<div>
<div></div>
<div class= "square-1"></div>
</div>
</div>
<div class= "game-square">
<div>
<div></div>
<div class= "square-2"></div>
</div>
</div>
<div class= "game-square">
<div>
<div></div>
<div class= "square-3"></div>
</div>
</div>
<div class= "game-square">
<div>
<div></div>
<div class= "square-4"></div>
</div>
</div>
<div class= "game-square">
<div>
<div></div>
<div class= "square-5"></div>
</div>
</div>
<div class= "game-square">
<div>
<div></div>
<div class= "square-6"></div>
</div>
</div>
<div class= "game-square">
<div>
<div></div>
<div class= "square-7"></div>
</div>
</div>
<div class= "game-square">
<div>
<div></div>
<div class= "square-8"></div>
</div>
</div>
<div class= "game-square">
<div>
<div></div>
<div class= "square-9"></div>
</div>
</div>
<div class= "game-square">
<div>
<div></div>
<div class= "square-0"><div>
</div>
</div>
<div class= "game-square">
<div>
<div></div>
<div class= "square-1"></div>
</div>
</div>
<div class= "game-square">
<div>
<div></div>
<div class= "square-2"></div>
</div>
</div>
<div class= "game-square">
<div>
<div></div>
<div class= "square-3"></div>
</div>
</div>
<div class= "game-square">
<div>
<div></div>
<div class= "square-4"></div>
</div>
</div>
</div>
<button id="reset-button">Reset</button>
</div>
<script src= "./script.js"></script>
</body>
</html>
I made my own implementation with notes; you can compare to see different approach/techniques:
//pick 8 colors
const colors = ["red","blue","green","yellow","orange","purple","brown","pink"];
//double the colors
const double = colors.concat(colors);
//randomize the colors
const matches = [];
for(let i = 0; i < 16; i ++) {
const random = Math.floor(Math.random() * double.length);
matches.push(double.splice(random,1)[0]);
}
//create variable that houses id of comparing square
let compareTo;
//create global click disable
let disable = false;
//on click function
function reveal(e) {
//prevent spam click during comparison
if(disable) return;
//shorten e.target.id to id
const id = e.target.id;
//reveal clicked square
e.target.classList.toggle("hidden");
//remove its onclick
e.target.onclick = null;
//if no squares being compared, store id
if(!compareTo){
compareTo = id;
} else {
//otherwise if square colors match
if(matches[compareTo] === matches[id]){
//reset id reference (keeping both reveal);
compareTo = null;
//win condition
if(!document.getElementsByClassName("hidden").length) setTimeout(()=>alert("YOU WIN!"),0);
} else {
//otherwise prevent spam click during reveal
disable = true;
//and hide both squares, must be in a timeout to be visible
setTimeout(()=> {
e.target.classList.toggle("hidden");
document.getElementById(compareTo).classList.toggle("hidden");
//add onclick back
e.target.onclick = ()=> reveal(event);
document.getElementById(compareTo).onclick = ()=> reveal(event);
//enable clicking
disable = false;
//and erase id reference;
compareTo = null;
},750);
}
}
}
//reference container for iteration
const container = document.getElementById("container");
//iterate squares rather than hard code into html
for(let i = 0; i < 16; i ++){
const square = document.createElement("div");
square.onclick = ()=> reveal(event);
square.classList.add("square");
//add class that hides color
square.classList.add("hidden");
//ids match indexes of color matches
square.setAttribute("id",i);
//assign corresponding color
square.style.backgroundColor = matches[i];
container.append(square);
}
#container {
width: 400px;
height: 400px;
display: flex;
flex-wrap: wrap;
background: blue;
border: 1px solid black;
}
.square {
width: 25%;
height: 25%;
border: 1px solid black;
box-sizing: border-box;
}
.hidden {
background-color: dimgray !important;
}
<div id="container">
</div>
You were very close. I am guessing the material you are reading is only focused on going up to 10 colors. These are the issues that pertain to this:
By looking at your CSS, your .square-X classes only go up to 9. It should go up to 15 (0 index basis)
In your JS, your colors initialization for loop condition is i < 10. It should be i < 16 since you are targeting 16 colors.
Also this particular line var colors = ["square-1" - "square-9"]; is confusing. This is supposed to simply initialize an array but you are assigning it some kind of string value
By fixing these items, the memory game will work as expected. See demo below:
var resetButton = document.getElementById("reset-button");
var colors = [];
for (var i = 0; i < 16; i++) {
colors.push("square-" + i);
}
function GameSquare(el, color) {
this.el = el;
this.isOpen = false;
this.isLocked = false;
this.el.addEventListener("click", this, false);
this.setColor(color);
}
GameSquare.prototype.handleEvent = function(e) {
switch (e.type) {
case "click":
if (this.isOpen || this.isLocked) {
return;
}
this.isOpen = true;
this.el.classList.add('flip');
checkGame(this);
}
}
GameSquare.prototype.reset = function() {
this.isOpen = false;
this.isLocked = false;
this.el.classList.remove('flip');
}
GameSquare.prototype.lock = function() {
this.isLocked = true;
this.isOpen = true;
}
GameSquare.prototype.setColor = function(color) {
this.el.children[0].children[1].classList.remove(this.color);
this.color = color;
this.el.children[0].children[1].classList.add(color);
}
var gameSquares = [];
function random(n) {
return Math.floor(Math.random() * n)
}
function getSomeColors() {
var colorscopy = colors.slice();
var randomColors = [];
for (var i = 0; i < 8; i++) {
var index = random(colorscopy.length);
randomColors.push(colorscopy.splice(index, 1)[0]);
}
return randomColors.concat(randomColors.slice());
}
function setupGame() {
var array = document.getElementsByClassName("game-square");
var randomColors = getSomeColors();
for (var i = 0; i < array.length; i++) {
var index = random(randomColors.length);
var color = randomColors.splice(index, 1)[0];
gameSquares.push(new GameSquare(array[i], color));
}
}
var firstSquare = null;
function checkGame(GameSquare) {
if (firstSquare === null) {
firstSquare = GameSquare;
return
}
if (firstSquare.color === GameSquare.color) {
firstSquare.lock();
GameSquare.lock();
} else {
var a = firstSquare;
var b = GameSquare;
setTimeout(function() {
a.reset();
b.reset();
}, 400);
}
firstSquare = null;
}
function randomizeColors() {
var randomColors = getSomeColors();
gameSquares.forEach(function(GameSquare) {
var color = randomColors.splice(random(randomColors.length), 1)[0];
GameSquare.setColor(color);
});
}
function clearGame() {
gameSquares.forEach(function(GameSquare) {
gameSquares.reset();
});
setTimeout(function() {
randomizeColors();
}, 500);
}
setupGame()
* {
padding: 0;
margin: 0;
}
.game-square {
box-sizing: border-box;
border: 1px solid #000;
width: 100px;
height: 100px;
position: relative;
overflow: hidden;
}
.game-square>div {
width: 100%;
height: 200%;
position: absolute;
top: 0;
transition: 400ms;
}
.game-square>div>div {
height: 50%;
}
.game-square>div>div:first-child {
background-color: grey;
}
.flip>div {
top: -100%;
}
.square-0 {
background-color: aqua;
}
.square-1 {
background-color: bisque;
}
.square-2 {
background-color: blue;
}
.square-3 {
background-color: blueviolet;
}
.square-4 {
background-color: brown;
}
.square-5 {
background-color: cadetblue;
}
.square-6 {
background-color: chartreuse;
}
.square-7 {
background-color: chocolate;
}
.square-8 {
background-color: coral;
}
.square-9 {
background-color: teal;
}
.square-10 {
background-color: hotpink;
}
.square-11 {
background-color: khaki;
}
.square-12 {
background-color: lime;
}
.square-13 {
background-color: turquoise;
}
.square-14 {
background-color: plum;
}
.square-15 {
background-color: red;
}
#game {
width: 400px;
height: 400px;
display: flex;
flex-direction: row;
flex-wrap: wrap;
border: 1px solid red;
}
#game {
width: 400px;
height: 400px;
display: flex;
flex-direction: row;
flex-wrap: wrap;
}
#reset-button {
position: absolute;
top: 90px;
}
<body>
<div class="container">
<div id="game">
<div class="game-square">
<div>
<div></div>
<div class=""></div>
</div>
</div>
<div class="game-square">
<div>
<div></div>
<div class="square"></div>
</div>
</div>
<div class="game-square">
<div>
<div></div>
<div class="square"></div>
</div>
</div>
<div class="game-square">
<div>
<div></div>
<div class="square"></div>
</div>
</div>
<div class="game-square">
<div>
<div></div>
<div class="square"></div>
</div>
</div>
<div class="game-square">
<div>
<div></div>
<div class="square"></div>
</div>
</div>
<div class="game-square">
<div>
<div></div>
<div class="square"></div>
</div>
</div>
<div class="game-square">
<div>
<div></div>
<div class="square"></div>
</div>
</div>
<div class="game-square">
<div>
<div></div>
<div class="square"></div>
</div>
</div>
<div class="game-square">
<div>
<div></div>
<div class="square"></div>
</div>
</div>
<div class="game-square">
<div>
<div></div>
<div class="square"></div>
</div>
</div>
<div class="game-square">
<div>
<div></div>
<div class="square"></div>
</div>
</div>
<div class="game-square">
<div>
<div></div>
<div class="square"></div>
</div>
</div>
<div class="game-square">
<div>
<div></div>
<div class="square"></div>
</div>
</div>
<div class="game-square">
<div>
<div></div>
<div class="square"></div>
</div>
</div>
<div class="game-square">
<div>
<div></div>
<div class="square"></div>
</div>
</div>
</div>
</div>
<button id="reset-button">Reset</button>
</body>
The issue seems to be that certain letters like g, y, q, etc. that have a tail that slopes downwards, do not allow for vertical centering. Here's an image to showcase the problem .
The characters in the green box are basically perfect, as they have no downward tail. Those in the red box demonstrate the problem.
I would like for all characters to be perfectly vertically centered. In the image, characters with a downward tail are not vertically centered. Is this possible to rectify?
Here is the fiddle that demonstrates the problem in full.
.avatar {
border-radius: 50%;
display: inline-block;
text-align: center;
width: 125px;
height: 125px;
font-size: 60px;
background-color: rgb(81, 75, 93);
font-family: "Segoe UI";
margin-bottom: 10px;
}
.character {
position: relative;
top: 50%;
transform: translateY(-50%);
line-height: 100%;
color: #fff;
}
<div class="avatar">
<div class="character">W</div>
</div>
<div class="avatar">
<div class="character">y</div>
</div>
Here is my solution using JS. The idea is to transform the element into an image in order to get its data as pixel then loop through them to find the top and bottom of each character and apply a translation to fix the alignment. This will work with dynamic font properties.
The code is not optimized but it highlight the main idea:
var elems = document.querySelectorAll(".avatar");
var fixes = [];
for (var i = 0; i < elems.length; i++) {
var current = elems[i];
domtoimage.toPixelData(current)
.then(function(im) {
/* Search for the top limit */
var t = 0;
for (var y = 0; y < current.scrollHeight; ++y) {
for (var x = 0; x < current.scrollWidth; ++x) {
var j = (4 * y * current.scrollHeight) + (4 * x);
if (im[j] == 255 && im[j + 1] == 255 && im[j + 2] == 255) {
t = y;
break;
}
}
}
/* Search the bottom limit*/
var b = 0;
for (var y = (current.scrollHeight - 1); y >= 0; --y) {
for (var x = (current.scrollWidth - 1); x >= 0; --x) {
var j = (4 * y * current.scrollHeight) + (4 * x);
if (im[j] == 255 && im[j + 1] == 255 && im[j + 2] == 255) {
b = current.scrollHeight - y;
break;
}
}
}
/* get the difference and apply a translation*/
var diff = (b - t)/2;
fixes.push(diff);
/* we apply the translation when all are calculated*/
if(fixes.length == elems.length) {
for (var k = 0; k < elems.length; k++) {
elems[k].querySelector('.character').style.transform = "translateY(" + fixes[k] + "px)";
}
}
});
}
.avatar {
border-radius: 50%;
display: inline-flex;
vertical-align:top;
justify-content: center;
align-items: center;
width: 125px;
height: 125px;
font-size: 60px;
background:
linear-gradient(red,red) center/100% 1px no-repeat,
rgb(81, 75, 93);
font-family: "Segoe UI";
margin-bottom: 10px;
}
.character {
color: #fff;
}
<script type="text/javascript" src="https://css-challenges.com/wp-content/themes/ronneby_child/js/dom-to-image.js"></script>
<div class="avatar">
<div class="character">W</div>
</div>
<div class="avatar">
<div class="character">y</div>
</div>
<div class="avatar">
<div class="character" style="font-size:35px">a</div>
</div>
<div class="avatar">
<div class="character" style="font-size:25px">2</div>
</div>
<div class="avatar">
<div class="character">o</div>
</div>
<div class="avatar">
<div class="character">|</div>
</div>
<div class="avatar">
<div class="character">#</div>
</div>
<div class="avatar">
<div class="character">Â</div>
</div>
<div class="avatar">
<div class="character" style="font-family:arial">Q</div>
</div>
<div class="avatar">
<div class="character">~</div>
</div>
<div class="avatar">
<div class="character">8</div>
</div>
<div class="avatar">
<div class="character">ä</div>
</div>
<div class="avatar">
<div class="character">ç</div>
</div>
<div class="avatar">
<div class="character">$</div>
</div>
<div class="avatar">
<div class="character">></div>
</div>
<div class="avatar">
<div class="character">%</div>
</div>
UPDATE
Here is a first optimization of the code:
var elems = document.querySelectorAll(".avatar");
var k = 0;
for (var i = 0; i < elems.length; i++) {
domtoimage.toPixelData(elems[i])
.then(function(im) {
var l = im.length;
/* Search for the top limit */
var t = 0;
for (var j = 0; j < l; j+=4) {
if (im[j+1] == 255) { /* Since we know the colors, we can only test the G composant */
t = Math.ceil((j/4)/125);
break;
}
}
/* Search the bottom limit*/
var b = 0;
for (var j = l - 1; j >= 0; j-=4) {
if (im[j+1] == 255) {
b = 125 - Math.ceil((j/4)/125);
break;
}
}
/* get the difference and apply a translation*/
elems[k].querySelector('.character').style.transform = "translateY(" + (b - t)/2 + "px)";
k++;
});
}
.avatar {
border-radius: 50%;
display: inline-flex;
vertical-align:top;
justify-content: center;
align-items: center;
width: 125px;
height: 125px;
font-size: 60px;
background:
linear-gradient(red,red) center/100% 1px no-repeat,
rgb(81, 75, 93);
font-family: "Segoe UI";
margin-bottom: 10px;
}
.character {
color: #fff;
}
<script type="text/javascript" src="https://css-challenges.com/wp-content/themes/ronneby_child/js/dom-to-image.js"></script>
<div class="avatar">
<div class="character">W</div>
</div>
<div class="avatar">
<div class="character">y</div>
</div>
<div class="avatar">
<div class="character" style="font-size:35px">a</div>
</div>
<div class="avatar">
<div class="character" style="font-size:25px">2</div>
</div>
<div class="avatar">
<div class="character">o</div>
</div>
<div class="avatar">
<div class="character">|</div>
</div>
<div class="avatar">
<div class="character">#</div>
</div>
<div class="avatar">
<div class="character">Â</div>
</div>
<div class="avatar">
<div class="character" style="font-family:arial">Q</div>
</div>
<div class="avatar">
<div class="character">~</div>
</div>
<div class="avatar">
<div class="character">8</div>
</div>
<div class="avatar">
<div class="character">ä</div>
</div>
<div class="avatar">
<div class="character">ç</div>
</div>
<div class="avatar">
<div class="character">$</div>
</div>
<div class="avatar">
<div class="character">></div>
</div>
<div class="avatar">
<div class="character">%</div>
</div>
I am using dom-to-image plugin for this.
Maybe there is a better answer, but it sounds like the only way to is to manually apply different styles depending on whether it is one of:
Capital letter
Lowercase with a tail
Lowercase with a stalk
Lowercase with neither
Now note that, in my understanding, the relative heights of tails and stalks I think is defined by the font. I'm not sure if there's a way to access that programatically - so you might need to adjust these values with the font.
Note also that this solution wouldn't work for supporting multiple languages - as you would need to define which category every single character fits in across dozens of different character sets.
const letters = ['a', 'b', 'y', 'X', 'c', 'y', 'A', 'B', 'Y'];
function getAdditionalClass(char){
//To do - fill arrays with the rest of the appropriate letters
if (['y', 'g'].includes(char)) {
return "tail";
}
if (['b', 'd'].includes(char)) {
return "stalk";
}
if (['a', 'c'].includes(char)) {
return "small";
}
return "capital";
}
letters.forEach(v => {
const avatar = document.createElement("div");
avatar.className = "avatar";
const character = document.createElement("div");
character.textContent = v;
character.className = `character ${getAdditionalClass(v)}`;
avatar.appendChild(character);
const root = document.getElementById("root");
root.appendChild(avatar);
});
.avatar {
border-radius: 50%;
display: block;
text-align: center;
width: 125px;
height: 125px;
font-size: 60px;
background-color: rgb(81, 75, 93);
font-family: "Segoe UI";
margin-bottom: 10px;
}
.character {
position: relative;
transform: translateY(-50%);
line-height: 100%;
color: #fff;
}
.small {
top: 45%;
}
.stalk {
top: 50%;
}
.tail {
top: 41%;
}
.capital {
top: 50%;
}
#root {
display: flex;
flex-flow: row wrap;
}
<div id = "root">
</div>
This is a tricky situation!
From what I can tell, this will be most difficult to make natively scalable (i.e. %, vw or vh values instead of px or em). If you need to make this look pretty on mobile or tablet, please consider using my solution with #media breakpoints.
My solution essentially detects if it is a lowercase element with a tail and adds a class to offset the height to compensate for the tail.
In my testing, it didn't appear that any additional handlers were required for capital letters or lower case letters without a tail. Be feel free to correct me if I'm wrong.
There's a JSFiddle if you want to mess around and change / test this solution.
var circles = document.getElementsByClassName('circle');
var tails = ['q', 'y', 'p', 'g', 'j'] ;
Array.from(circles).forEach(render);
function render(element) {
if(element.innerText == element.innerText.toLowerCase() &&
tails.includes(element.innerText)) {
element.className += " scale";
}
}
.circle {
height: 150px;
width: 150px;
background-color: #bbb;
border-radius: 50%;
display: inline-block;
text-align: center;
vertical-align: middle;
line-height: 150px;
font-size: 50px;
}
.scale {
line-height: 135px;
}
<div>
<div class="circle">W</div>
<div class="circle">X</div>
</div>
<div>
<div class="circle">y</div>
<div class="circle">t</div>
</div>
Let me know your thoughts and if I've missed anything. It'd be cool to get a final solution for this as I've had similar issues in the past myself!
You would probably need a helperclass for this, so that you can translate the lowercase letters more than the capital letters. A simple script can easily put these helper classes on automatically.
Hope this solves the problem for you :)
.avatar {
border-radius: 50%;
display: block;
text-align: center;
width: 125px;
height: 125px;
font-size: 60px;
background-color: rgb(81, 75, 93);
font-family: "Segoe UI";
margin-bottom: 10px;
}
.character {
position: relative;
top: 50%;
line-height: 100%;
color: #fff;
}
.character-lowercase {
transform: translateY(-60%);
}
.character-capital {
transform: translateY(-50%);
}
<div class="avatar">
<div class="character character-capital">W</div>
</div>
<div class="avatar">
<div class="character character-lowercase">y</div>
</div>
I need help to do a simple text slider in jQuery or JavaScript.
I need a slider with animation so that the text moves from right to left.
Within my code I have also pagination, where I need highlight which text is active.
This is all of what I have, I need to be very simple.
All answers on the internet are so complicated.
Can someone help me?
.active{
color:red;
}
<div class="buttons">
<button name="prev">Prev</button>
<button name="next">Next</button>
</div>
<div class="content">
<div class="slide">
<p>content od slide</p>
</div>
<div class="slide">
<p>content od slide</p>
</div>
<div class="slide">
<p>content od slide</p>
</div>
</div>
<div class="paginator">
<div class="pagin-tracker">1</div>
<div class="pagin-tracker active">1</div>
<div class="pagin-tracker">1</div>
</div>
You can try this one.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.slider {
}
.slider__wrap {
overflow: hidden;
}
.slide {
width: 100%;
display: inline-block;
text-align: center;
}
.content {
will-change: transform;
white-space: nowrap;
transition: transform 0.3s;
}
</style>
</head>
<body>
<div id="slider" class="slider">
<div class="buttons">
<button name="prev">Prev</button>
<button name="next">Next</button>
</div>
<div class="slider__wrap">
<div class="content" style="transform: translate(-100%);" data-active="1"> <!-- if you need to set initial position to the second slider, or you can use translate(0) to set it to the first slide -->
<div class="slide">
<p>content od slide 1</p>
</div>
<div class="slide">
<p>content od slide 2</p>
</div>
<div class="slide">
<p>content od slide 3</p>
</div>
</div>
</div>
<div class="paginator">
<div class="pagin-tracker">1</div>
<div class="pagin-tracker active">1</div>
<div class="pagin-tracker">1</div>
</div>
</div>
<script>
const slider = document.getElementById('slider');
const sliderWrap = slider.querySelector('.slider__wrap');
const sliderContent = sliderWrap.querySelector('.content');
const sliderButtons = slider.querySelector('.buttons');
const buttonPrev = sliderButtons.querySelector('button[name="prev"]');
const buttonNext = sliderButtons.querySelector('button[name="next"]');
const pages = Array.from(slider.querySelectorAll('.pagin-tracker'));
const pagesCount = pages.length;
const slidesCount = sliderContent.querySelectorAll('.slide').length;
let activeIndex = sliderContent.getAttribute('data-active');
const updatePaginator = () => {
for (let i = 0; i < pagesCount; i++) {
pages[i].classList.remove('active');
}
if (pages[activeIndex]) {
pages[activeIndex].classList.add('active');
}
};
const applyStyle = () => {
sliderContent.setAttribute('data-active', activeIndex);
sliderContent.style.cssText = `transform: translate(-${activeIndex * 100}%);`;
updatePaginator();
};
buttonPrev.addEventListener('click', () => {
if (activeIndex > 0) {
activeIndex--;
applyStyle();
}
}, false);
buttonNext.addEventListener('click', () => {
if (activeIndex < slidesCount - 1) {
activeIndex++;
applyStyle();
}
}, false);
</script>
</body>
</html>
You can use something like this and extend as per you requirement.
https://codepen.io/anon/pen/MqRpKg
HTML
<div class="slide-wrap">
<div class="slide-mask">
<ul class="slide-group">
<li class="slide">this</li>
<li class="slide">is</li>
<li class="slide">a</li>
<li class="slide">simple</li>
<li class="slide">slider</li>
</ul>
</div>
<div class="slider-nav">
<ul></ul>
</div>
</div>
JQuery:
var $slide = $('.slide'),
$slideGroup = $('.slide-group'),
$bullet = $('.bullet')
var slidesTotal = ($slide.length - 1),
current = 0,
isAutoSliding = true;
$bullet.first().addClass('current');
var clickSlide = function() {
//stop auto sliding
window.clearInterval(autoSlide);
isAutoSliding = false;
var slideIndex = $bullet.index($(this));
updateIndex(slideIndex);
};
var updateIndex = function(currentSlide) {
if(isAutoSliding) {
if(current === slidesTotal) {
current = 0;
} else {
current++;
}
} else {
current = currentSlide;
}
$bullet.removeClass('current');
$bullet.eq(current).addClass('current');
transition(current);
};
var transition = function(slidePosition) {
var slidePositionNew = (slidePosition ) * 500;
$slideGroup.animate({
'left': '-' + slidePositionNew + 'px'
});
};
var autoSlide = window.setInterval(updateIndex, 2000);
$( "li.slide" ).each(function( index ) {
$('.slider-nav').append('<span class="bullet">'+index+'</span>');
});
var $bullet = $('.bullet');
$bullet.on( 'click', clickSlide);
CSS
body {
background: rgb(191, 76, 76);
}
/* slider
----------------------*/
.slide-wrap {
margin: 5% auto 0;
width: 540px;
}
.slide-mask {
position: relative;
overflow: hidden;
height: 100px;
}
.slide-group {
position: absolute;
top: 0px;
left: 0;
}
.slide {
display:inline-block;
height: 100px;
width:500px;
font: 100 90px/135px "lato";
font-size: 2em;
color: #fff;
text-align: center;
text-transform: uppercase;
}
/* nav
----------------------*/
.slide-nav {
text-align: center;
border: 1px solid red;
height: 30px;
color: red;
}
.slide-nav ul {
margin: 0;
padding: 0;
}
.slide-nav li {
border: 1px solid red;
width: 100px;
cursor: pointer;
color: red;
}
.slide-nav li.current {
background: rgb(144, 39, 39);
}
.slider-nav {
width: 300px;
text-alignt: center;
margin-left:40%;
}
span.bullet {
display:inline-block;
width: 30px;
cursor: pointer;
}
I'm writing a simple html game. I want to compare the red cards' numbers to random numbers. If any one of random numbers equal to red cards' numbers, then dynamically add "BINGO" text to red square's back class when user flip red cards. It's like bingo game, user don't know which cards have "BINGO" strings before they flip red cards. I have problem with comparing array numbers to front class numbers and dynamically add "BINGO" string to red cards. Can somebody help please?
JSFIDDLE is here: http://jsfiddle.net/7emqLztp/28/
$(".treasure").flip();
var howMany = 3;
var min = 2;
var max = 5;
var a = new Array();
while (a.length < howMany) {
var n = Math.floor(Math.random() * (max - min) + 0.5) + min;
if (a.indexOf(n) == -1) {
a.push(n);
}
}
$("#button").click(function () {
$('.num').text(a)
});
.table
{
display: table;
border-collapse:separate;
/*border-spacing: 5px;*/
/*border: 1px solid #fff;*/
}
.table-row
{
display: table-row;
}
.table-cell
{
text-align: center;
display: table-cell;
border: 0.5px solid #231f20;
vertical-align: middle;
width: 50px;
height: 50px;
}
.treasure
{
background-color: red;
}
<script src="https://cdn.rawgit.com/nnattawat/flip/master/dist/jquery.flip.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<head>
<script src="https://cdn.rawgit.com/nnattawat/flip/master/dist/jquery.flip.min.js"></script>
</head>
<div class="table">
<div class="table-row">
<div class="table-cell">
1
</div>
<div class="table-cell treasure">
<div class="front">2</div>
<div class="back"></div>
</div>
<div class="table-cell treasure">
<div class="front">3</div>
<div class="back"></div>
</div>
<div class="table-cell treasure">
<div class="front">4</div>
<div class="back"></div>
</div>
<div class="table-cell treasure">
<div class="front">5</div>
<div class="back"></div>
</div>
<div class="table-cell">
6
</div>
</div>
</div>
<button id="button">Random Num</button>
<div class="num"></div>
Please have a look at this updated code. I'm pretty sure this is working.
$(".treasure").flip().find(".back").text("-")
var cardCount = 3;
var bingoCards = [];
do {
let n = Math.floor(Math.random() * 4) + 2;
if (bingoCards.indexOf(n) === -1) {
bingoCards.push(n)
let item = $(".treasure")[n-2];
$(item).find(".back").text("BINGO")
}
} while (bingoCards.length < cardCount)
$("#button").click(function() {
$("#result").html(`The numbers are: <b>${bingoCards.join(", ")}</b>`)
});
.table {
display: table;
border-collapse: separate;
/*border-spacing: 5px;*/
/*border: 1px solid #fff;*/
}
.table-row {
display: table-row;
}
.table-cell {
text-align: center;
display: table-cell;
border: 0.5px solid #231f20;
vertical-align: middle;
width: 50px;
height: 50px;
}
.treasure {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.rawgit.com/nnattawat/flip/master/dist/jquery.flip.min.js"></script>
<script src="https://cdn.rawgit.com/nnattawat/flip/master/dist/jquery.flip.min.js"></script>
<div class="table">
<div class="table-row">
<div class="table-cell">1</div>
<div class="table-cell treasure">
<div class="front">2</div><div class="back"></div>
</div>
<div class="table-cell treasure">
<div class="front">3</div><div class="back"></div>
</div>
<div class="table-cell treasure">
<div class="front">4</div><div class="back"></div>
</div>
<div class="table-cell treasure">
<div class="front">5</div><div class="back"></div>
</div>
<div class="table-cell">6</div>
</div>
</div>
<button id="button">Random Numbers</button>
<div id="result"></div>