What is wrong with my code - It does not close - javascript

What I am trying to achieve is to change the name of the btn when opening and closing, however, when I test the functions individually it works fine however when I combine both function in one btn it doesn't could someone help, please.
What I am trying to achieve is to change the name of the btn when opening and closing, however, when I test the functions individually it works fine however when I combine both function in one btn it doesn't could someone help, please.
// JavaScript Document
let myBtn = document.querySelector("#btn");
let myBase = document.querySelector("#base");
let status = false;
myBase.style.marginTop = "-250px";
function myFunction() {
if (status === false) {
myBase.style.marginTop = "-120px";
status = true;
} else if (status = true) {
myBase.style.marginTop = "-250px"
status = false;
}
}
//myBtn.onclick = myFunction;
myBtn.innerHTML = "<P>OPEN</P>";
function nameFunction() {
if (status === false) {
myBtn.innerHTML = "<P>OPEN</P>";
status = true;
} else if (status = true) {
myBtn.innerHTML = "<P>CLOSE</P>";
status = false;
}
}
// myBtn.onclick = nameFunction;
function twoFunction() {
myFunction();
nameFunction();
}
myBtn.onclick = twoFunction;
#btn {
height: 30px;
width: 50px;
color: white;
background: orange;
line-height: 30px;
margin-top: 50px;
margin-left: 250px;
padding: 10px;
cursor: pointer
}
#base {
padding: 10px;
background: pink;
width: 200px;
height: 110px;
margin-top: 0px;
transition: 1s ease-in-out;
}
#base>div {
height: 30px;
width: auto;
background: red;
}
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div id="btn">
<p>OPEN</p>
</div>
<div id="base">
<div></div>
<div></div>
<div></div>
</div>
</body>
<script src="js/scripts.js"></script>
</html>

You have two main problems with the code:
if (status = true) will perform assignment, not equality check.
You should use == or === for that. Although since you're checking a boolean, you don't need an else if - if status is not false, then it can only be true. You can just do
if (status === false) {
/* ... code if false ... */
} else {
/* ... code if true ... */
}
You set status = false and status = true twice. First in myFunction, then in nameFunction. So when you the handler is invoked myFunction checks the status, sees status is false switches it to true and then when nameFunction runs, status is now true, where it should have been false.
you can extract the code to change the status value and only call it from one place. I moved it to twoFunction after both other functions have completed:
// JavaScript Document
let myBtn = document.querySelector("#btn");
let myBase = document.querySelector("#base");
let status = false;
myBase.style.marginTop = "-250px";
function myFunction() {
console.log(status)
if (status === false) {
myBase.style.marginTop = "-120px";
} else { //no need for else if
myBase.style.marginTop = "-250px"
}
}
//myBtn.onclick = myFunction;
myBtn.innerHTML = "<P>OPEN</P>";
function nameFunction() {
if (status === false) {
myBtn.innerHTML = "<P>OPEN</P>";
} else { //no need for else if
myBtn.innerHTML = "<P>CLOSE</P>";
}
}
// myBtn.onclick = nameFunction;
function twoFunction() {
myFunction();
nameFunction();
//only set the status once
if (status === false) {
status = true;
} else {
status = false;
}
}
myBtn.onclick = twoFunction;
#btn {
height: 30px;
width: 50px;
color: white;
background: orange;
line-height: 30px;
margin-top: 50px;
margin-left: 250px;
padding: 10px;
cursor: pointer
}
#base {
padding: 10px;
background: pink;
width: 200px;
height: 110px;
margin-top: 0px;
transition: 1s ease-in-out;
}
#base>div {
height: 30px;
width: auto;
background: red;
}
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div id="btn">
<p>OPEN</p>
</div>
<div id="base">
<div></div>
<div></div>
<div></div>
</div>
</body>
<script src="js/scripts.js"></script>
</html>

From your code, else if (status = true) should be else if (status == true) or else if (status === true)

Related

js function stops acting

![Text](https://stackoverfl
var obj = {
count: 1
}
function elementSet()
{
if(obj.count=1){
document.getElementById("text").textContent = "graa";}
if(obj.count=2){
document.getElementById("text").textContent = "graa";}
if(obj.count=3){
document.getElementById("text").textContent = "graa";}
}
function back()
{
if(obj.count>1)
{
obj.count = obj.count -1;
document.getElementById("back").style.display = "block";
document.getElementById("page_num").textContent = obj.count;
}
}
function forth()
{
if(obj.count<3){
obj.count = obj.count +1;
document.getElementById("page_num").textContent = obj.count;
document.getElementById("forth").style.display = "block";
if (obj.count>3){
document.getElementById("forth").style.display = "none";}
}
}
.colx1 {
color: #e1992e;
/* height: 3px; */
font-size: 2.1ch;
margin-right: 80%;
inline-size: auto;
border-color: #e1992e;
border-radius: 11ch;
}
.colx2 {
color: #e1992e;
font-size: 2.1ch;
inline-size: auto;
margin-top: -3%;
margin-left: 80%;
border-color: #e1992e;
border-radius: 11ch;
}
.colabount
{
width: 170px;
}
.row {
display: inline;
}
.body
{
text-align: center;
max-height: 100%;
}
.button {
border-color: #e1992e;
}
.page_num
{
color: black;
size: 13ch;
text-align: center;
}
.text
{
color: blanchedalmond;
size: 12ch;
}
<!DOCTYPE html>
<html>
<head>
<title>films</title>
<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body class="body">
<div class="container external internal" id="content">
<h2 id="text" class="text" type="textContent"> its the f</h2>
<div class="row">
<button class="colx1" id="back" type="button" onclick="back(),elementSet()"><b>back</d></button>
<button class="colx2" id="forth" type="button" onclick="forth(),elementSet()"><b>forth</d></button>
</div>
<div class="page_num"><b id ="page_num">1</b></div>
</div>
</body>
</html>
ow.com/image.jpg)
i tried to create external obj that contain count its working.
the page content will change acording to the count number.
the proble starts when im calling 'elementSet' = {checking abount obj.count and
changing the page acordingly}
THE PROBLEM : when elementSet runs back() and forth() not working anymore!
your mistake is that:
in java script = is assignment. for example: let a = 0;
we assignment 0 to a. now a is 0.
and we have == and ===. these are use for comparison in logics and Condition. for example:
let a = 0;
a == 0 && console.log("yes");
there are some different between == and ===. you can read that in a link!

Sequential animations on HTML element

guys. I'm trying to create a group of sequential "animations" through css classes on my buttons, but i keep getting a problem where all my buttons receive the effect on the same time and not one after another.
The function playAllSequence should hightlight each button one after another following the sequence present in an array.
I've already tried to put the setTimeOut function inside a closure and tried changed my declaration to let instead of var.
What am i missing?
Thanks in advance
// Get number of buttons on the document
var numberOfButtons = document.querySelectorAll(".btn").length;
var collectionButtonsClicked = [];
var collectionOfRandomColors = [];
var buttonsColors = ["blue", "green", "red", "yellow"];
var gameTitle = document.querySelector("#level-title");
// detecting clicks on the buttons
for ( let i = 0; i < numberOfButtons; i++) {
document.querySelectorAll(".btn")[i].addEventListener("click", function () {
collectionButtonsClicked.push(this.id);
// call click animation function
clickAnimation ();
// Only checks when arrays have the same length so the user have to click all the sequence again
if (collectionButtonsClicked.length === collectionOfRandomColors.length) {
checkClick();
}
})};
// detecting button press to start the game
document.addEventListener("keydown", function (event) {
if (event.key === "a") {
gameTitle.innerHTML = "Game Started";
generateRandomColor();
playAllSequence();
}
});
// check if the click is correct
function checkClick () {
// if correct - Generate new color, disable buttons and play the sequence on all buttons
let arrayRandomStringfied = JSON.stringify(collectionOfRandomColors);
let arrayClickedStringfied = JSON.stringify(collectionButtonsClicked);
if (arrayRandomStringfied === arrayClickedStringfied) {
generateRandomColor();
playAllSequence();
console.log("acertou!")
// erasing click array so the player has to click all the color again
collectionButtonsClicked = [];
} else {
//call fail animation function
failAnimation();
// function to reset the arrays and the title
restartGame();
console.log("errou!")
}
}
//Generate random color and return array - User will have to follow this colors
function generateRandomColor () {
let randomIndex = Math.floor(Math.random() * 4);
collectionOfRandomColors.push(buttonsColors[randomIndex]);
return collectionOfRandomColors;
}
function playAllSequence () {
// disabling all buttons
for ( let i = 0; i < numberOfButtons; i++) {
document.querySelectorAll(".btn")[i].disabled = true;
}
for ( let i = 0; i < collectionOfRandomColors.length; i++ ) {
doSetTimeOut(i);
}
// Enabling all buttons again
for ( let i = 0; i < numberOfButtons; i++) {
document.querySelectorAll(".btn")[i].disabled = false;
}
}
function doSetTimeOut (i) {
let activeButton = document.querySelector("." + collectionOfRandomColors[i]);
// Add pressed effect
activeButton.classList.add("pressed");
// Remove pressed effect after 1 second
setTimeout(function() {
activeButton.classList.remove("pressed")
}, 1000);
}
function clickAnimation () {
}
function failAnimation () {
}
function restartGame () {
collectionOfRandomColors = [];
collectionButtonsClicked = [];
gameTitle.innerHTML = "Press A key to Start";
}
body {
text-align: center;
background-color: #011F3F;
}
#level-title {
font-family: 'Press Start 2P', cursive;
font-size: 3rem;
margin: 5%;
color: #FEF2BF;
}
.container {
display: block;
width: 50%;
margin: auto;
}
.btn {
margin: 25px;
display: inline-block;
height: 200px;
width: 200px;
border: 10px solid black;
border-radius: 20%;
}
.game-over {
background-color: red;
opacity: 0.8;
}
.red {
background-color: red;
}
.green {
background-color: green;
}
.blue {
background-color: blue;
}
.yellow {
background-color: yellow;
}
.pressed {
box-shadow: 0 0 20px white;
background-color: grey;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Simon</title>
<link rel="stylesheet" href="styles.css">
<link href="https://fonts.googleapis.com/css?family=Press+Start+2P" rel="stylesheet">
</head>
<body>
<h1 id="level-title">Press A Key to Start</h1>
<div class="container">
<div class="row">
<div type="button" id="green" class="btn green">
</div>
<div type="button" id="red" class="btn red">
</div>
</div>
<div class="row">
<div type="button" id="yellow" class="btn yellow">
</div>
<div type="button" id="blue" class="btn blue">
</div>
</div>
</div>
<script src="index.js" charset="utf-8"></script>
</body>
</html>
Well, I don't see your sample code to animate even the first button.
If you need independent separate events to happen '1 by 1' visually, you might use a i*1000 as a setTimeout second argument.
If not, here's the code doing something close to what you want to achieve, i believe. Define a function that sets the props you need (box-shadow in this example) for an element taken by index, and sets timeout for a function that will remove the props and call the first function again with the next index:
function animateBtnsSequence( i ){
var btns = document.querySelectorAll(".btn");
btns[i].style.boxShadow = '0 0 20px 1px white';
window.setTimeout(function(){
btns[i].style.boxShadow = '';
if( btns[i+1] )
animateBtnsSequence( i + 1 );
}, 1000)
}
function playAllSequence () {
animateBtnsSequence( 0 );
}

some javascript functions isn't working in cordova android app

I'm new to Cordova, and I'm trying to build an android app
I copied my files into www file and replaced its files with mine
and build apk but when running it on my phone the first two buttons only are working (Equal weight / Unequal weight) while the (add more/ reset/ result buttons ) are not, but when I'm trying to check my code as a web page it works perfectly, as you might see in the snippet
I also tried to keep the cordova.js file and the index.js with my app.js but it didn't work
I tried to add cordova.js and index.js (the files that created automatically when creating a project with Cordova) but it didn't work
//declare the main buttons and divs
const btn1 = document.querySelector('.eqbtn'),
btn2 = document.querySelector('.uneqbtn'),
div1 = document.querySelector('.eqdiv'),
div2 = document.querySelector('.wrap-sub')
div_2 = document.querySelector('.uneqdiv');
//add event listeners to the main buttons
btn1.addEventListener('click', equalFunc);
btn2.addEventListener('click', unequalFunc);
//switch between two keys
function equalFunc() {
togFunc(div1, div_2, btn1, btn2);
resetFunc('.eqdiv', div1);
}
function unequalFunc() {
togFunc(div_2, div1, btn2, btn1);
resetFunc('.wrap-sub', div2);
}
function togFunc(one, two, a, b) {
a.classList.add('active');
b.classList.remove('active');
one.style.display = 'block';
two.style.display = 'none';
}
//declare the equal addmore button
const btnplus = document.querySelector('.eqmore');
const unbtnplus = document.querySelector('.un-eqmore');
//fire when addmore button get fired
btnplus.addEventListener('click', () => {
if (checkIn('.eqdiv') === false) {
errIn();
} else {
creatIn(div1);
}
});
//fire when uneqaddmore get clicked
unbtnplus.addEventListener('click', () => {
if (checkIn('.wrap-sub') === false) {
errIn();
} else {
creatIn(div2);
}
})
//check the value of the inputs
function checkIn(nav) {
let bool;
document.querySelectorAll(`${nav} input`).forEach((elem) => {
if (elem.value === '' || elem.value < 0) {
elem.style.borderColor = '#f86868';
bool = false;
} else {
elem.style.borderColor = '#D1D1D1';
}
});
return bool;
}
//create the input and assign it's value
function creatIn(dnav) {
if (dnav === div1) {
const dive = document.createElement('div');
dive.innerHTML = `<input type ='number'/>`;
dnav.insertBefore(dive, btnplus);
} else {
const sp1 = document.createElement('div'),
sp2 = document.createElement('div');
sp1.innerHTML = `<input type ='number'>`;
sp2.innerHTML = `<input type ='number'>`;
document.querySelector('.div2-1').appendChild(sp2);
document.querySelector('.div2-2').appendChild(sp1);
}
}
//fire an error if the user insert wrong value
function errIn() {
const errdiv = document.createElement('div');
errdiv.innerHTML = `Please fill inputs with positive values`;
errdiv.classList.add('errdiv');
document.querySelector('.wrap').insertAdjacentElement('beforeend', errdiv);
setTimeout(() => errdiv.remove(), 1800);
}
//fire when the reset button get clicked
function resetFunc(x, y) {
document.querySelectorAll(`${x} input`).forEach(reset => {
reset.remove();
});
document.querySelector('#output').innerHTML = '';
creatIn(y);
}
//reset all the inputs
document.querySelector('.reset').addEventListener('click', () => resetFunc('.eqdiv', div1));
document.querySelector('.un-reset').addEventListener('click', () => resetFunc('.wrap-sub', div2));
//fire when result button get fired
document.querySelector('.result').addEventListener('click', resFunc);
document.querySelector('.un-result').addEventListener('click', unresFunc);
//declare result function when result button get clicked
function resFunc() {
if (checkIn('.eqdiv') === false) {
errIn();
} else {
let arr = [];
document.querySelectorAll('.eqdiv input').forEach(res => arr.push(Number(res.value)));
const num = arr.length;
const newarr = arr.reduce((a, b) => a + b);
const mean = newarr / num;
const resarr = [];
arr.forEach(re => resarr.push((re - mean) * (re - mean)));
const newresarr = resarr.reduce((c, v) => c + v);
const norDev = Math.sqrt(newresarr / (num - 1));
const dev = norDev / Math.sqrt(num);
let mpv;
if (!isNaN(dev)) {
mpv = `${mean.toFixed(3)} ± ${dev.toFixed(3)}`;
} else {
mpv = `${mean.toFixed(3)}`;
}
displayResult(mpv);
}
}
function unresFunc() {
if (checkIn('.wrap-sub') === false) {
errIn();
} else {
let allweight = [],
allValues = [],
subMeanArray = [],
sub = [],
semiFinal = [];
document.querySelectorAll('.div2-2 input').forEach(w => allweight.push(Number(w.value)));
const sumWeight = allweight.reduce((n, m) => n + m);
document.querySelectorAll('.div2-1 input').forEach(s => allValues.push(Number(s.value)));
for (i = 0; i < allweight.length; i++) {
subMeanArray.push(allweight[i] * allValues[i]);
}
const sumMean = subMeanArray.reduce((a, b) => a + b);
const mean = sumMean / sumWeight;
allValues.forEach(s => sub.push(s - mean));
for (i = 0; i < allweight.length; i++) {
semiFinal.push(allweight[i] * sub[i] * sub[i]);
}
const alFinal = semiFinal.reduce((a, b) => a + b);
const nDev = Math.sqrt(alFinal / allweight.length);
const Dev = nDev / Math.sqrt(sumWeight);
let mpv;
if (isNaN(Dev)) {
mpv = ` : No choice but the only value you gave which is ${allValues[0].toFixed(3)}`;
} else {
mpv = `${mean.toFixed(3)} ± ${Dev.toFixed(3)}`;
}
displayResult(mpv);
}
}
function displayResult(wow) {
document.querySelector('#output').innerHTML = `The Result is ${wow}`;
}
.wrap>div {
display: none;
}
/* .uneqdiv{
display: none;
} */
.container {
padding-top: 100px;
width: max-content;
padding-bottom: 50px;
}
.wrap {
margin-top: 50px;
}
.wrap-sub {
display: flex;
}
.div2-1 {
margin-right: 5px;
}
button {
outline: none;
transition: border .3s;
}
.active,
.active:focus {
border-color: #46d84d;
}
button.reset:hover,
button.un-reset:hover {
border-color: #f86868;
}
button.eqmore:hover,
button.un-eqmore:hover {
border-color: #46d84d;
}
.errdiv {
height: 40px;
width: 100%;
background-color: #df4f4f;
color: #ffffff;
display: flex !important;
justify-content: center;
align-items: center;
}
#output {
padding-top: 20px;
}
h6 {
margin: 0;
}
.tes {
display: inline-block;
}
#media(max-width: 700px) {
.container {
display: flex;
flex-direction: column;
align-items: center;
width: 100%;
}
.container>h2 {
font-size: 2rem;
}
button {
width: 75%;
max-width: 20rem;
}
.wrap {
display: flex;
flex-direction: column;
align-items: center;
width: 90%;
}
.eqdiv {
text-align: center;
}
.eqdiv input {
max-width: 20rem;
width: 75%;
}
.eqdiv button {
display: block;
margin-left: auto;
margin-right: auto;
}
.uneqdiv {
text-align: center;
width: 100%;
}
.wrap-sub input {
max-width: 25rem;
width: 100%;
}
.uneqdiv .wrap-sub {
width: 100%;
margin-top: 40px;
margin-bottom: 15px;
display: flex;
flex-direction: column;
align-items: center;
}
.wrap-sub h6 {
font-size: 1.4rem;
}
.tes button {
width: 100%;
}
}
<html>
<head>
<meta content="utf-8">
<meta name="viewport" content="initial-scale=1, width=device-width, viewport-fit=cover">
<link rel="stylesheet" type="text/css" href="css/normalize.css">
<link rel="stylesheet" type="text/css" href="css/skeleton.css">
<link rel="stylesheet" type="text/css" href="css/index.css">
<title>survey</title>
</head>
<body>
<div class="container">
<h2 class="jui">Please select the wanted method</h2>
<button class="eqbtn">equal weight</button>
<button class="uneqbtn">unequal weight</button>
<div class="wrap">
<div class="eqdiv">
<h4>Enter the equal values</h4>
<div>
<input type="number" class="init">
</div>
<button class="eqmore">add more +</button>
<button class="reset">reset</button>
<button class="result button-primary">result</button>
</div>
<div class="uneqdiv">
<h4>Enter the unequal values</h4>
<div class="wrap-sub">
<div class="div2-1">
<h6>The Measurements</h6>
<input type="number" class="un-init">
</div>
<div class="div2-2">
<h6>The Weights</h6>
<input type="number" class="un-weight">
</div>
</div>
<div class="tes">
<button class="un-eqmore">add more +</button>
<button class="un-reset">reset</button>
<button class="un-result button-primary">result</button>
</div>
</div>
</div>
<div id="output"></div>
</div>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript" src="js/app.js"></script>
</body>
</html>

JS & Jquery: functions goes crazy after being called.

in the game, when it shows the colors that you need to click and you click on the wrong color, after it alerts the colors start going crazy, the 2 functions that possibly doing that are in lines 24 and 55, but i cant find the problem in both.
i want after the fail alert the colors run normaly.
how can i fix this?
here is the code:
CodePen
// Setting Variables
var gameStatus = false;
var strict = false;
var playerTurn = true;
var colors = ['green', 'red', 'yellow', 'blue'];
var colorsPicked = ['red', 'red', 'yellow', 'blue', 'green'];
var colorsClicked = [];
var level = 1;
var index = 0;
var lindex = 0;
var showOn = false;
// Game Status Function
$('#start').click(function(){
if(gameStatus == false){
gameStatus = true;
gameStart();
}
});
// Game Start Function
function gameStart(){
// left this function for later
}
// Chaning color buttons
$('.cubes').click(function(e){
if(playerTurn == true){
$(e.target).addClass(e.target.id);
colorsClicked.push(e.target.id);
setTimeout(function(){
$(e.target).removeClass(e.target.id);
}, 500);
// Player's turn & check if got the right colors
if(colorsPicked[index] !== colorsClicked[index]){
alert('Failed! Try again.');
showColorStart();
index=0;
} else {
if(colorsPicked.length == colorsClicked.length){
level++;
randomColor();
showColorStart();
}
}
index++;
} else {
return;
}
});
// Random Color Picking Function
function randomColor(){
var random = Math.floor(Math.random() * 4);
colorsPicked.push(colors[random]);
}
// Colors Showing at Start of a level
function showColorStart(){
if(showOn == false){
showOn == true;
playerTurn = false;
lindex = 0;
setInterval(function(){
if(colorsPicked[lindex] == 'green'){
$('#green').addClass('green');
} else if(colorsPicked[lindex] == 'red'){
$('#red').addClass('red');
} else if(colorsPicked[lindex] == 'yellow'){
$('#yellow').addClass('yellow');
} else if(colorsPicked[lindex] == 'blue'){
$('#blue').addClass('blue');
}
setTimeout(function(){
$('#green').removeClass('green');
$('#red').removeClass('red');
$('#yellow').removeClass('yellow');
$('#blue').removeClass('blue');
}, 1000);
if(lindex == colorsPicked.length){
clearInterval();
lindex = 0;
index = 0;
playerTurn = true;
}
lindex++;
}, 1500);
} else {
return;
}
}
showColorStart();
<DOCTYPE html>
<html>
<head>
<title>Simon Game</title>
<link href="style.css" type="text/css" rel="stylesheet"/>
<link href='bootstrap.min.css' type="text/css"/>
</head>
<body>
<div class="container">
<div class="menu">
<input type='button' value='Start' id='start' class='btn'>
<input type='button' value='Restart' id='restart' class='btn'>
<input type='button' value='Strict' id='strict' class='btn'>
</div>
<div class='board'>
<div class='display'><p id='disp'></p></div>
<br>
<table>
<tbody>
<tr>
<td class='cubes' id='green'></td>
<td class='cubes' id='red'></td>
</tr>
<tr>
<td class='cubes' id='yellow'></td>
<td class='cubes' id='blue'></td>
</tr>
</tbody>
</table>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="app.js"></script>
</body>
</html>
On your code you are never actually clearing the interval, and that might be causing the issue. There are some minor things, like instead of if(playerTurn == true) you could just do if(playerTurn)these not causing the issue you are having but it's just good practice.
Not sure how this whole thing should work, but clearing the interval does seems to fix the issue you were having.
// Setting Variables
var gameStatus = false;
var strict = false;
var playerTurn = true;
var colors = ['green', 'red', 'yellow', 'blue'];
var colorsPicked = ['red', 'red', 'yellow', 'blue', 'green'];
var colorsClicked = [];
var level = 1;
var index = 0;
var lindex = 0;
var showOn = false;
// Game Status Function
$('#start').click(function(){
if(!gameStatus){
gameStatus = true;
gameStart();
}
});
// Game Start Function
function gameStart(){
// left this function for later
}
// Chaning color buttons
$('.cubes').click(function(e){
if(playerTurn){
$(e.target).addClass(e.target.id);
colorsClicked.push(e.target.id);
setTimeout(function(){
$(e.target).removeClass(e.target.id);
}, 500);
// Player's turn & check if got the right colors
console.log(colorsPicked[index], colorsClicked[index]);
if(colorsPicked[index] !== colorsClicked[index]){
alert('Failed! Try again.');
showColorStart();
index = 0;
} else {
if(colorsPicked.length == colorsClicked.length){
level++;
randomColor();
showColorStart();
}
}
index++;
} else {
return;
}
});
// Random Color Picking Function
function randomColor(){
var random = Math.floor(Math.random() * 4);
colorsPicked.push(colors[random]);
}
// Colors Showing at Start of a level
function showColorStart(){
if(!showOn){
showOn == true;
playerTurn = false;
lindex = 0;
// save timer
var gameTimer = setInterval(function(){
if(colorsPicked[lindex] == 'green'){
$('#green').addClass('green');
} else if(colorsPicked[lindex] == 'red'){
$('#red').addClass('red');
} else if(colorsPicked[lindex] == 'yellow'){
$('#yellow').addClass('yellow');
} else if(colorsPicked[lindex] == 'blue'){
$('#blue').addClass('blue');
}
setTimeout(function(){
$('#green').removeClass('green');
$('#red').removeClass('red');
$('#yellow').removeClass('yellow');
$('#blue').removeClass('blue');
}, 1000);
if(lindex === colorsPicked.length){
// clear timer
clearInterval(gameTimer);
lindex = 0;
index = 0;
playerTurn = true;
}
lindex++;
}, 1500);
} else {
return;
}
}
showColorStart();
#import url('https://fonts.googleapis.com/css?family=Orbitron');
body {
background-color: #000;
margin: 0;
padding: 0;
}
.container {
margin: 0 auto;
text-align: center;
padding: 20px;
}
.menu {
margin-bottom: 20px;
}
.display {
width: 130px;
height: 40px;
background-color: #282828;
margin: 0 auto;
text-align: center;
font-family: Orbitron, sans-serif;
}
table {
margin: 0 auto;
}
.cubes {
width: 150px;
height: 150px;
}
#green {
border: 2px solid green;
border-right: 2px solid red;
}
#red {
border: 2px solid red;
border-bottom: 2px solid blue;
}
#yellow {
border: 2px solid yellow;
}
#blue {
border: 2px solid blue;
}
.green {
background-color: green;
}
.red {
background-color: red;
}
.yellow {
background-color: yellow;
}
.blue {
background-color: blue;
}
#disp {
font-size: 12px;
color: #000;
padding: 8px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Game</title>
</head>
<body>
<div class="container">
<div class="menu">
<input type='button' value='Start/Restart' id='start' class='btn'>
<input type='button' value='Strict' id='strict' class='btn'>
</div>
<div class='board'>
<div class='display'><p id='disp'></p></div>
<br>
<table>
<tbody>
<tr>
<td class='cubes' id='green'></td>
<td class='cubes' id='red'></td>
</tr>
<tr>
<td class='cubes' id='yellow'></td>
<td class='cubes' id='blue'></td>
</tr>
</tbody>
</table>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</body>
</html>
Codepen link https://codepen.io/azs06/pen/eGRgeK
Instead of calling showColorStart() in case of failure you can also call $('#start').click(); to reset the game.
When you are calling showColorStart() in case of failure it is only resetting index and that too after showColorStart() is called. So there might me some variables that you need to reset before calling showColorStart().

Adding images to my array?

I would like to know if there's any way to add images to the arrays of my Slot machine? Right now i've just been able to add numbers in the array.
So far i got this, i know there's only one choice in my array, it's on purpose:
var arr = ["#7.png"];
// var arr = [5];
var credits = 10;
function freezeCheck() {
if (document.getElementById("hold1").checked == true || document.getElementById("hold2").checked == true || document.getElementById("hold3").checked == true) {
// if any is checked, freeze hold buttons.
document.getElementById("hold1").checked = false;
document.getElementById("hold2").checked = false;
document.getElementById("hold3").checked = false;
document.getElementById("hold1").disabled = true;
document.getElementById("hold2").disabled = true;
document.getElementById("hold3").disabled = true;
} else if (document.getElementById("hold1").disabled == true) {
// if any diabled, enable (unfreeze) all hold buttons.
document.getElementById("hold1").disabled = false;
document.getElementById("hold2").disabled = false;
document.getElementById("hold3").disabled = false;
document.getElementById("reel1").classList.remove('hold');
document.getElementById("reel2").classList.remove('hold');
document.getElementById("reel3").classList.remove('hold');
}
};
function getNumbers() {
if(document.getElementById("hold1").checked == false){
document.getElementById("reel1").innerHTML = arr[Math.floor(Math.random() * arr.length)];
} if (document.getElementById("hold2").checked == false){
document.getElementById("reel2").innerHTML = arr[Math.floor(Math.random() * arr.length)];
} if (document.getElementById("hold3").checked == false){
document.getElementById("reel3").innerHTML = arr[Math.floor(Math.random() * arr.length)];
}
updateScore();
insertCoins();
};
function calculateScore() {
document.getElementById('credits').innerHTML = credits;
}
// Win, three alike.
function updateScore() {
if(document.getElementById("reel1").textContent == document.getElementById("reel2").textContent && document.getElementById("reel1").textContent == document.getElementById("reel3").textContent){
credits += document.getElementById("reel1").textContent * 10;
} else if("reel1" != "reel2"){
credits -= 2;
}
};
function insertCoins() {
if (credits <1){
document.getElementById("spin").disabled = true;
}
};
function freezeReel(num) {
if (document.getElementById('hold'+num).checked == true) {
// Unfreeze reel
document.getElementById("hold"+num).checked = false;
document.getElementById("reel"+num).classList.remove('hold');
} else {
// Freeze reel:
document.getElementById("hold"+num).checked = true;
document.getElementById("reel"+num).classList.add('hold');
}
}
* {
margin: 0;
padding: 0;
}
.marginauto {
margin: 0 auto;
}
.button-wrapper {
text-align: center;
margin-top: 15%;
}
.hold-wrapper {
text-align: center;
margin: 10px;
font-size: 48px;
}
.holdbutton {
width: 140px;
height: 200px;
visibility: hidden;
}
.credits {
width: 250px;
height: 100px;
margin: 0 auto;
text-align: center;
}
.reel-wrapper {
width: 1280px;
text-align: center;
margin-top: 10px;
background-color: #ffffff;
}
.button {
background-color: white;
}
.reels {
background-color: #ffffff;
display: inline-block;
font-size: 48px;
text-align: center;
width: 150px;
height: 200px;
border: 1px solid black;
border-radius: 2px;
}
.reels.hold {
border-color: blue;
background: #ccc;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link type="text/css" rel="stylesheet" href="stylesheet.css" />
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title> </title>
</head>
<body>
<header></header>
<div class="button-wrapper">
<input id="spin" type="button" onClick="getNumbers(); freezeCheck(); calculateScore();" value="Spin" />
</div>
<div class="reel-wrapper marginauto">
<div id="reel1" onClick="freezeReel(1);" class="reels"></div>
<div id="reel2" onClick="freezeReel(2);" class="reels"></div>
<div id="reel3" onClick="freezeReel(3);" class="reels"></div>
</div>
<div class="hold-wrapper">
<input id="hold1" type="checkbox" value="Hold" class="holdbutton" />
<input id="hold2" type="checkbox" value="Hold" class="holdbutton" />
<input id="hold3" type="checkbox" value="Hold" class="holdbutton" />
</div>
<div class="credits">Your Credits: <span id="credits"></span></div>
<script src="script.js"></script>
</body>
</html>
You should use the backgroundImage javascript property and provide value with a source from the array arr.
Refer code:
var arr = ['image1.png', 'image2.png', 'image3.png'];
var credits = 10;
function freezeCheck() {
if (document.getElementById("hold1").checked == true || document.getElementById("hold2").checked == true || document.getElementById("hold3").checked == true) {
// if any is checked, freeze hold buttons.
document.getElementById("hold1").checked = false;
document.getElementById("hold2").checked = false;
document.getElementById("hold3").checked = false;
document.getElementById("hold1").disabled = true;
document.getElementById("hold2").disabled = true;
document.getElementById("hold3").disabled = true;
} else if (document.getElementById("hold1").disabled == true) {
// if any diabled, enable (unfreeze) all hold buttons.
document.getElementById("hold1").disabled = false;
document.getElementById("hold2").disabled = false;
document.getElementById("hold3").disabled = false;
document.getElementById("reel1").classList.remove('hold');
document.getElementById("reel2").classList.remove('hold');
document.getElementById("reel3").classList.remove('hold');
}
};
function getNumbers() {
if(document.getElementById("hold1").checked == false){
document.getElementById("reel1").backgroundImage = "url(" + arr[0] + ")";
} if (document.getElementById("hold2").checked == false){
document.getElementById("reel2").backgroundImage = "url(" + arr[1] + ")";
} if (document.getElementById("hold3").checked == false){
document.getElementById("reel3").backgroundImage = "url(" + arr[2] + ")";
}
updateScore();
insertCoins();
};
function calculateScore() {
document.getElementById('credits').innerHTML = credits;
}
// Win, three alike.
function updateScore() {
if(document.getElementById("reel1").textContent == document.getElementById("reel2").textContent && document.getElementById("reel1").textContent == document.getElementById("reel3").textContent){
credits += document.getElementById("reel1").textContent * 10;
} else if("reel1" != "reel2"){
credits -= 2;
}
};
function insertCoins() {
if (credits <1){
document.getElementById("spin").disabled = true;
}
};
function freezeReel(num) {
if (document.getElementById('hold'+num).checked == true) {
// Unfreeze reel
document.getElementById("hold"+num).checked = false;
document.getElementById("reel"+num).classList.remove('hold');
} else {
// Freeze reel:
document.getElementById("hold"+num).checked = true;
document.getElementById("reel"+num).classList.add('hold');
}
}
* {
margin: 0;
padding: 0;
}
.marginauto {
margin: 0 auto;
}
.button-wrapper {
text-align: center;
margin-top: 15%;
}
.hold-wrapper {
text-align: center;
margin: 10px;
font-size: 48px;
}
.holdbutton {
width: 140px;
height: 200px;
visibility: hidden;
}
.credits {
width: 250px;
height: 100px;
margin: 0 auto;
text-align: center;
}
.reel-wrapper {
width: 1280px;
text-align: center;
margin-top: 10px;
background-color: #ffffff;
}
.button {
background-color: white;
}
.reels {
background-color: #ffffff;
display: inline-block;
font-size: 48px;
text-align: center;
width: 150px;
height: 200px;
border: 1px solid black;
border-radius: 2px;
}
.reels.hold {
border-color: blue;
background: #ccc;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link type="text/css" rel="stylesheet" href="stylesheet.css" />
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title> </title>
</head>
<body>
<header></header>
<div class="button-wrapper">
<input id="spin" type="button" onClick="getNumbers(); freezeCheck(); calculateScore();" value="Spin" />
</div>
<div class="reel-wrapper marginauto">
<div id="reel1" onClick="freezeReel(1);" class="reels"></div>
<div id="reel2" onClick="freezeReel(2);" class="reels"></div>
<div id="reel3" onClick="freezeReel(3);" class="reels"></div>
</div>
<div class="hold-wrapper">
<input id="hold1" type="checkbox" value="Hold" class="holdbutton" />
<input id="hold2" type="checkbox" value="Hold" class="holdbutton" />
<input id="hold3" type="checkbox" value="Hold" class="holdbutton" />
</div>
<div class="credits">Your Credits: <span id="credits"></span></div>
<script src="script.js"></script>
</body>
</html>
innerHTML stands for standard font in your page and it will only shows text. Since in your array, the value of it is #7.png and it will only display #7.png.
Adding the following code will create img tag in your html code with the images being random.
var elem = document.createElement("img");
elem.setAttribute("src", arr[Math.floor(Math.random() * arr.length)]);
elem.setAttribute("alt", "Slotimg");
document.getElementById("reel1").appendChild(elem);
However if you can create a default image, i would suggest you just add a Img tag in your div, and just change the src attribute by src code, it is going to be much easier and effiecnt

Categories

Resources