Toggle page color with JS - javascript

I'm trying to use JS to change my page's color theme by click a button, and by clicking it again to change it back (i.e. toggle). So far this is my JS code:
var i = 0;
function changeColor() {
if (i%2 == 0) {
switchBlue();
} else {
switchGreen();
}
i++;
}
function switchBlue() {
document.getElementById('color-wrap-01').style.backgroundColor = "#07184a";
document.getElementById('color-wrap-02').style.backgroundColor = "#006385";
document.getElementById('color-wrap-03').style.backgroundColor = "#82baba";
document.getElementById('color-wrap-04').style.backgroundColor = "#082644";
document.getElementById('box').style.backgroundColor = "#d0dddd";
document.getElementById('vl-01').style.borderLeft = "4px solid blue";
document.getElementById('vl-02').style.borderLeft = "4px solid blue";
var footerText = document.getElementsByClassName('footer-text');
for (i = 0; i < 3; i++) {
footerText[i].style.color = "#8eb7ba";
}
var headerText = document.getElementsByClassName('header-text');
for (i = 0; i < 4; i++) {
headerText[i].style.color = "#81babd";
}
var subTitle = document.getElementsByClassName('sub-title');
for (i = 0; i < 11; i++) {
subTitle[i].style.color = "#008688";
}
}
function switchGreen() {
document.getElementById('color-wrap-01').style.backgroundColor = "#074946";
document.getElementById('color-wrap-02').style.backgroundColor = "#00865F";
document.getElementById('color-wrap-03').style.backgroundColor = "#81BA88";
document.getElementById('color-wrap-04').style.backgroundColor = "#084330";
document.getElementById('box').style.backgroundColor = "#D7DDD0";
document.getElementById('vl-01').style.borderLeft = "4px solid green";
document.getElementById('vl-02').style.borderLeft = "4px solid green";
var footerText = document.getElementsByClassName('footer-text');
for (i = 0; i < 3; i++) {
footerText[i].style.color = "green";
}
var headerText = document.getElementsByClassName('header-text');
for (i = 0; i < 4; i++) {
headerText[i].style.color = "green";
}
var subTitle = document.getElementsByClassName('sub-title');
for (i = 0; i < 11; i++) {
subTitle[i].style.color = "green";
}
}
with this html:
<div id="color-wrap-01">
<div class="container">
<div class="row top-header">
<div class="col-sm-6">
<p align="left">Welcome, Guest Login Sign Up</p>
</div>
<div class="col-sm-6">
<p align="right">Stay Updated: Subscribe via RSS Email Updates</p>
</div>
</div>
</div>
AND this button:
<button onclick="changeColor()">COLOUR</button>
The first color change works, but then after that the button doesn't switch back to Green. Any help is appreciated!

If you actually want to toggle between two colors, you can do like this :
var colorSwitch = '';
function changeColor() {
if (colorSwitch === '') {
switchBlue();
colorSwitch = 'blue';
} else {
switchGreen();
colorSwitch = '';
}
}
Thats just an idea, but you may not need an iterator.
You can test that here : https://jsfiddle.net/qwu41fno/

Related

HTML: click the button, it changes color. Then click the button, however, it doesn't change to original color

I want to achieve a functionality where I click the correct answer, it turns into green. If click the wrong answer, it turns into red. Next I want to add a functionality: if I click the right-answer button twice, it first changes into specific color with first click, and changes into white with second click. However, this additional functionality comes with a bug. It can't turn into original color.
I try to use hello to achieve this additional functionality, but somewhere seems to be wrong...
let b = document.querySelectorAll('.false');
let hello = -1;
document.querySelector('.true').addEventListener('click', function() {
if (hello === 0) {
document.querySelector('.true').style.backgroundColor = 'white';
document.getElementById('check').innerHTML = null;
}
hello = 0;
document.querySelector('.true').style.backgroundColor = 'red';
document.querySelector('#check').innerHTML = 'Correct!';
document.querySelector('#check').style.color = 'green';
for (let i = 0; i < b.length; i++) {
b[i].style.backgroundColor = 'white';
}
})
for (let i = 0; i < b.length; i++) {
b[i].addEventListener('click', function() {
if (hello === 1) {
b[i].style.backgroundColor = 'white';
document.getElementById('check').innerHTML = null;
}
hello = 1;
b[i].style.backgroundColor = 'green';
document.querySelector('#check').innerHTML = 'Incorrect.';
document.querySelector('#check').style.color = 'red';
b[b.length - i - 1].style.backgroundColor = 'white';
document.querySelector('.true').style.backgroundColor = 'white';
})
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Trivia!</title>
</head>
<body>
<h3>IP version</h3>
<button class="false" style="background-color: white">IPv3</button>
<button class="true" style="background-color: white">IPv4</button>
<button class="false" style="background-color: white">IPv5</button>
<p id="check"></p>
</body>
</html>
Even though your if statement runs, you overwrite styles after that. You got 2 cases:
Where it is first time clicking the correct button,
It is second time clicking the correct button
So a simple if - else will solve this:
(I also made changes on some styling, because in your code correct button were red, and wrong buttons were green.)
let b = document.querySelectorAll('.false');
let hello = -1;
document.querySelector('.true').addEventListener('click', function () {
if (hello === 0) {
hello = -1;
document.querySelector('.true').style.backgroundColor = 'white';
document.getElementById('check').innerHTML = null;
} else {
hello = 0;
document.querySelector('.true').style.backgroundColor = 'green';
document.querySelector('#check').innerHTML = 'Correct!';
document.querySelector('#check').style.color = 'green';
}
for (let i = 0; i < b.length; i++) {
b[i].style.backgroundColor = 'white';
}
})
for (let i = 0; i < b.length; i++) {
b[i].addEventListener('click', function () {
if (hello === 1) {
b[i].style.backgroundColor = 'white';
document.getElementById('check').innerHTML = null;
}
hello = 1;
b[i].style.backgroundColor = 'red';
document.querySelector('#check').innerHTML = 'Incorrect.';
document.querySelector('#check').style.color = 'red';
b[b.length - i - 1].style.backgroundColor = 'white';
document.querySelector('.true').style.backgroundColor = 'white';
})
}
<h3>IP version</h3>
<button class="false" style="background-color: white">IPv3</button>
<button class="true" style="background-color: white">IPv4</button>
<button class="false" style="background-color: white">IPv5</button>
<p id="check"></p>
You just need to add a return keyword inside the conditional checking hello === 0, as shown below:
let b = document.querySelectorAll('.false');
let hello = -1;
document.querySelector('.true').addEventListener('click', function() {
if (hello === 0) {
document.querySelector('.true').style.backgroundColor = 'white';
document.getElementById('check').innerHTML = null;
return; // THIS IS ADDED
}
hello = 0;
document.querySelector('.true').style.backgroundColor = 'red';
document.querySelector('#check').innerHTML = 'Correct!';
document.querySelector('#check').style.color = 'green';
for (let i = 0; i < b.length; i++) {
b[i].style.backgroundColor = 'white';
}
})
// .......
BTW, you must swap the 'red' and 'green' strings in your code where you style the background-color CSS property, because right now when we click the wrong button, it is made green (where it should have been made red).
So the correct code will be:
let b = document.querySelectorAll('.false');
let hello = -1;
document.querySelector('.true').addEventListener('click', function() {
if (hello === 0) {
document.querySelector('.true').style.backgroundColor = 'white';
document.getElementById('check').innerHTML = null;
return
}
hello = 0;
document.querySelector('.true').style.backgroundColor = 'green'; // CHANGED HERE
document.querySelector('#check').innerHTML = 'Correct!';
document.querySelector('#check').style.color = 'green';
for (let i = 0; i < b.length; i++) {
b[i].style.backgroundColor = 'white';
}
})
for (let i = 0; i < b.length; i++) {
b[i].addEventListener('click', function() {
if (hello === 1) {
b[i].style.backgroundColor = 'white';
document.getElementById('check').innerHTML = null;
}
hello = 1;
b[i].style.backgroundColor = 'red'; // CHANGED HERE
document.querySelector('#check').innerHTML = 'Incorrect.';
document.querySelector('#check').style.color = 'red';
b[b.length - i - 1].style.backgroundColor = 'white';
document.querySelector('.true').style.backgroundColor = 'white';
})
}
You can achieve in this way too.
document.querySelectorAll(".false").forEach((value) => {
value.addEventListener("click", () => {
let currentColor = document.getElementById(value.id);
currentColor.style.backgroundColor =
currentColor.style.backgroundColor === "red" ? "white" : "red";
});
});
document.querySelectorAll(".true").forEach((value) => {
value.addEventListener("click", () => {
let currentColor = document.getElementById(value.id);
currentColor.style.backgroundColor =
currentColor.style.backgroundColor === "green" ? "white" : "green";
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<title>Trivia!</title>
</head>
<body>
<h3>IP version</h3>
<button id="1" class="false" style="background-color: white;">IPv3</button>
<button id="2" class="true" style="background-color: white;">IPv4</button>
<button id="3" class="false" style="background-color: white;">IPv5</button>
<p id="check"></p>
</body>
</html>

What to do when looping repeats in 2 different areas

The code gets the values of the input and sends it to the textarea, but when you add more than one title the values are repeated in the result of the titles, for example, the DESCRIPTIONS of title 1 are the same as in title 2, why does this happen? and how to make it work without changing the purpose?
Run the code in codepen.io or jsfiddle.net
This is what happens:
This is what should happen:
function result() {
var inp2 = document.getElementsByName("inp2");
var titu = document.getElementsByName("titu");
var res = document.getElementById("result");
res.value = "";
if (titu[0]) {
for (var k = 0; k < titu.length; k++) {
if (titu[k].value.trim() != '') {
res.value += `<div>
<span>${titu[k].value.trim()}</span>
</div>
<ul>\n`;
for (var j = 0; j < inp2.length; j++) {
if (inp2[j].value.trim() != '') {
res.value += `<li>${inp2[j].value.trim()}</li>\n`;
}
}
}
}
}else {
console.log("test")
res.value += `<ul>\n`;
for (var l = 0; l < inp2.length; l++) {
if (inp2[l].value.trim() != '') {
res.value += `<li>${inp2[l].value.trim()}</li>\n`;
}
}
}
};
// -----------------------------------------
if (document.getElementById("add2")) {
let cont2 = 1;
document.getElementById("add2").onclick = function clone2() {
let container2 = document.getElementById("output2");
let tempLinha2 = document.querySelector('#template2');
let clone2 = document.importNode(tempLinha2.content, true);
const label2 = clone2.querySelector("label");
label2.htmlFor = cont2;
clone2.querySelector("input").className = cont2;
container2.appendChild(clone2);
cont2++;
};
document.getElementById("del2").onclick = function del2() {
document.querySelector('#output2 #linha2:last-child').remove();
};
}
// ---------------------------------------
if (document.getElementById("addtit")) {
let cont3 = 1;
document.getElementById("addtit").onclick = function clone3() {
let container3 = document.getElementById("output2");
let tempLinha3 = document.querySelector('#template3');
let clone3 = document.importNode(tempLinha3.content, true);
const label3 = clone3.querySelector("label");
label3.htmlFor = cont3;
clone3.querySelector("input").className = cont3;
container3.appendChild(clone3);
cont3++;
document.getElementById('add2').id = 'add3';
document.getElementById('del2').id = 'del3';
};
document.getElementById("deltit").onclick = function deltit() {
document.querySelector('#output2 #alg:last-child').remove();
document.getElementById('add3').id = 'add2';
document.getElementById('del3').id = 'del2';
};
}
// -----------------------------------------
if (document.getElementById("add3")) {
let cont4 = 1;
document.getElementById("add3").onclick = function clone4() {
let container4 = document.getElementById("output3");
let tempLinha4 = document.querySelector('#template2');
let clone4 = document.importNode(tempLinha4.content, true);
const label4 = clone4.querySelector("label");
label4.htmlFor = cont4;
clone4.querySelector("input").className = cont4;
container4.appendChild(clone4);
cont4++;
};
document.getElementById("del3").onclick = function del4() {
document.querySelector('#output3 #linha2:last-child').remove();
};
}
<div class="container">
<button id="addtit">+ TITLE</button>
<button id="deltit">- TITLE</button>
<button id="add2">+ DESCRIPTION</button>
<button id="del2">- DESCRIPTION</button>
<div id="output2"></div>
<div class='botoes'>
<button onclick="result()" id='done'>DONE</button>
</div>
<div class="header"><span class="title">RESULT</span>
</div>
<div class="linha"><textarea id="result"></textarea>
</div>
</div>
<!-- template 2 -->
<template id="template2">
<div class="linha" id="linha2"><div class="coluna1"><label for="0">DESCRIPTION:</label></div><div class="coluna2"><input name="inp2" class="0" type="text"/></div>
</div>
</template>
<!-- template 3 -->
<template id="template3">
<div id="alg">
<div class="linha"><div class="coluna1"><label for="0">TITLE:</label></div><div class="coluna2"><input name="titu" class="0" type="text"/></div>
</div>
<div class="linha" id="linha3"><div class="coluna1"><label for="0">DESCRIPTION:</label></div><div class="coluna2"><input name="inp2" class="0" type="text"/></div>
</div>
<div id="output3"></div>
</div>
</template>
Ok. it's because this part of code in function result:
if (titu[0]) {
for (var k = 0; k < titu.length; k++) {
if (titu[k].value.trim() != '') {
res.value += `<div>
<span>${titu[k].value.trim()}</span>
</div>
<ul>\n`;
for (var j = 0; j < inp2.length; j++) {
if (inp2[j].value.trim() != '') {
res.value += `<li>${inp2[j].value.trim()}</li>\n`;
}
}
}
}
}
your titles have the same names : 'titu' , and your descriptions have same names : 'inp2', and you have two nested loops, for each title, loop on description, and it results as you see.
it's better to change your code and make different names and ids
by the way. if you persist to do not change your code, you should use one loop for both of them, like this code
if (titu[0]) {
for (var k = 0; k < titu.length; k++) {
if (titu[k].value.trim() != '') {
res.value += `<div>
<span>${titu[k].value.trim()}</span>
</div>
<ul>\n`;
if (inp2[k].value.trim() != '') {
res.value += `<li>${inp2[k].value.trim()}</li>\n`;
}
}
}
}
UPDATE
for the case of more description for each title, you have to change the code of onClick methods of Title+ and Description+, the added title and all of its description must have same parent, and after doing that, it's possible to solve the problem like this . (assuming the parent that I already have said has class name 'parent')
function result() {
var parents = document.querySelectorAll(".parent")
parents.forEach(function(parent){
var title = parent.querySelector("titu");
var descriptions = parent.querySelectorAll("inp2");
var res = document.getElementById("result");
if (title.value.trim() != '') {
res.value += `<div>
<span>${title.value.trim()}</span>
</div>
<ul>\n`;
}
descriptions.forEach(function(inp2){
if (inp2.value.trim() != '') {
res.value += `<li>${inp2.value.trim()}</li>\n`;
}
});
});
}
notice that this code could work after modifying Title+ and Description+ events and add same parent with class name parent to title and descriptions inputs

Style and change text content of children based on click

I am trying to style a single div and change the text content based on whether the user clicks on the item or not.
At the moment the code is extremely repetitive and I am looking for a method that will help me rewrite it to both work more efficiently and look cleaner.
Thank you.
let lvl0,
lvl1,
lvl2;
lvl0 = document.querySelector('.level-wrapper').children[0];
lvl1 = document.querySelector('.level-wrapper').children[1];
lvl2 = document.querySelector('.level-wrapper').children[2];
lvl0.addEventListener('click', changeStyle0);
lvl1.addEventListener('click', changeStyle1);
lvl2.addEventListener('click', changeStyle2);
function changeStyle0() {
document.querySelector('.text-header').textContent = levelTitle[0];
var showStyle = document.querySelector('.level-wrapper').children[0];
showStyle.style.opacity = '1';
showStyle.style.backgroundColor = '#95a5a6';
showStyle.style.border = '2px solid white';
showStyle.style.boxSizing = 'border-box';
console.log(showStyle);
}
function changeStyle1() {
document.querySelector('.text-header').textContent = levelTitle[1];
var showStyle = document.querySelector('.level-wrapper').children[1];
showStyle.style.opacity = '1';
showStyle.style.backgroundColor = '#95a5a6';
showStyle.style.border = '2px solid white';
showStyle.style.boxSizing = 'border-box';
console.log(showStyle);
}
function changeStyle2() {
document.querySelector('.text-header').textContent = levelTitle[2];
var showStyle = document.querySelector('.level-wrapper').children[2];
showStyle.style.opacity = '1';
showStyle.style.backgroundColor = '#95a5a6';
showStyle.style.border = '2px solid white';
showStyle.style.boxSizing = 'border-box';
console.log(showStyle);
}
var levelTitle = ["Question about Drinks/Soda/Water.", "Question about Portion Control/Meals.", "Question about Salt/Sugar."];
The method document.querySelector returns you only the first element in the document that fit the selector. To get an array of all the fits elements in the document, you have to use document.querySelectorAll method. For example:
const elements = document.querySelectorAll('.level-wrapper');
elemets[2].children[0].style = ...;
I think that this code is taking care of your issue:
const elements = document.querySelectorAll('.level-wrapper');
function showStyle(index, childIdx) {
elements[index].children[childIdx].style.opacity = '1';
elements[index].children[childIdx].style.backgroundColor = '#95a5a6';
elements[index].children[childIdx].style.border = '2px solid white';
elements[index].children[childIdx].style.boxSizing = 'border-box';
//console.log(levelStyle[index]);
}
function hideStyle(index, childIdx) {
elements[index].children[childIdx].style.opacity = '1';
elements[index].children[childIdx].style.backgroundColor = 'transparent';
elements[index].children[childIdx].style.border = 'none';
elements[index].children[childIdx].style.boxSizing = 'unset';
//console.log(levelStyle[index]);
}
/*for (let i = 0; i < elements.length; i++) {
for (let j = 0; j < elements[i].children.length; j++) {
showStyle(i,j);
}
}*/
for (let i = 0; i < elements.length; i++) {
for (let j = 0; j < elements[i].children.length; j++) {
(function (index) {
elements[i].children[j].onclick = function () {
elements[i].children[j].is_show = !elements[i].children[j].is_show;
if (elements[i].children[j].is_show) {
showStyle(i,j);
} else {
hideStyle(i,j);
}
}
})(j + i*elements[i].children.length);
}
}
<div class="level-wrapper">
<div>aaa</div>
<div>bbb</div>
<div>ccc</div>
<div>ddd</div>
</div>
<br><br>
<div class="level-wrapper">
<div>eee</div>
<div>fff</div>
<div>ggg</div>
<div>hhh</div>
</div>
This method ended up working for me.
Here is the Javascript:
function styleChange() {
const elements = document.getElementsByClassName("level");
for (let i = 0; i < elements.length; i++) {
elements[i].onclick = function () {
let el = elements[0];
while (el) {
if (el.tagName === "LI") {
el.classList.remove("active");
}
el = el.nextSibling;
}
this.classList.add("active");
};
}
}
styleChange();
Here is the html:
<ul class="level-wrapper">
<li class="level">
</a>1</li>
<li class="level">
</a>2</li>
<li class="level">
</a>3</li>
</ul>
And finally the css:
.active {
background-color: #95a5a6;
opacity: 1;
box-sizing: border-box;
border: 2px solid #fff;
}

onmouseover show only one submenu ( Javascript )

Good day,
trying to make a small menu only with Javascript and got a problem that onmouseover event shows all submenus and not only one.
this is the part of the code that suppose to change style.display to block.
var ul = document.getElementById("navMainId"),
var liDropdown = ul.getElementsByClassName("dropdown");
for (var i = 0; i < liDropdown.length; i++) {
liDropdown[i].style.display = "inline-block";
liDropdown[i].onmouseover = function () {
var ul = document.getElementById("navMainId"),
dropdown = ul.getElementsByClassName("dropdown-content");
for (var i = 0; i < dropdown.length; i++) {
dropdown[i].style.display = "block";
}
}
liDropdown[i].onmouseleave = function () {
var ul = document.getElementById("navMainId"),
dropdown = ul.getElementsByClassName("dropdown-content");
for (var i = 0; i < dropdown.length; i++) {
dropdown[i].style.display = "none";
}
}
}
How can i change the code to make it work ?
here is whole code on Fiddle ( ssry it is a mess ) : https://jsfiddle.net/apvsnzt5/1/
I've updated the fiddle:
https://jsfiddle.net/apvsnzt5/3/
All you needed to do was change
dropdown = ul.getElementsByClassName("dropdown-content");
to
dropdown = this.getElementsByClassName("dropdown-content");
So that it targets the "this" (being the LI you are hovered over) rather than finding the "dropdown-content" inside the UL.
Also do it on the onmouseleave.
Seems you have incorrect reference to container when mouser over. You need concrete content based on your mosue position.
var dropdown = this.getElementsByClassName("dropdown-content");
try updated fiddle
add the following to your css part
.dropdown-content{
display:none ! important;
}
a:hover+.dropdown-content{
display:block ! important;
}
it will works fine.
var menuCont = document.createElement("div");
document.body.appendChild(menuCont);
var ulMain = document.createElement("ul");
menuCont.appendChild(ulMain);
ulMain.className = "navMain";
ulMain.id = "navMainId";
/****** MENU ******/
// Software
var liSoftware = document.createElement("li");
liSoftware.className = "menu dropdown";
ulMain.appendChild(liSoftware);
var aSoftware = document.createElement("a");
aSoftware.className = "menuName dropbtn";
aSoftware.href = "#";
aSoftware.textContent = "Test1";
liSoftware.appendChild(aSoftware);
// GeCoSoft
var liGeco = document.createElement("li");
liGeco.className = "menu dropdown";
ulMain.appendChild(liGeco);
var aGeco = document.createElement("a");
aGeco.className = "menuName dropbtn";
aGeco.href = "#";
aGeco.textContent = "Test2";
liGeco.appendChild(aGeco);
/******* Submenu *******/
// Software Sub
var divSubSoft = document.createElement("div");
divSubSoft.className = "dropdown-content";
liSoftware.appendChild(divSubSoft);
var aSub1 = document.createElement("a"),
aSub2 = document.createElement("a");
aSub1.className = "menuSubName";
aSub1.textContent = "SubMenu1";
aSub1.href = "#";
aSub2.className = "menuSubName";
aSub2.textContent = "SubMenu2";
aSub2.href = "#";
divSubSoft.appendChild(aSub1);
divSubSoft.appendChild(aSub2);
// Gecosoft Sub
var divSubGeco = document.createElement("div");
divSubGeco.className = "dropdown-content";
liGeco.appendChild(divSubGeco);
var aSub3 = document.createElement("a"),
aSub4 = document.createElement("a");
aSub3.className = "menuSubName";
aSub3.textContent = "Submenu3";
aSub3.href = "#";
aSub4.className = "menuSubName";
aSub4.textContent = "SubMenu4"
aSub4.href = "#";
divSubGeco.appendChild(aSub3);
divSubGeco.appendChild(aSub4);
/****** MENU STYLE ******/
var i = "";
ulMain.style.listStyleType = "none";
ulMain.style.margin = "0px";
ulMain.style.padding = "0px";
ulMain.style.overflow = "hidden";
ulMain.style.backgroundColor = "rgb(232, 225, 225)";
var ul = document.getElementById("navMainId"),
li = ul.getElementsByTagName("li");
for (var i = 0; i < li.length; i++) {
li[i].style.cssFloat = "left";
}
var a = ul.getElementsByTagName("a");
for (var i = 0; i < a.length; i++) {
a[i].style.display = "inline-block";
a[i].style.color = "black";
a[i].style.textAlign = "center";
a[i].style.padding = "14px 16px";
a[i].style.textDecoration = "none";
a[i].onmouseover = function () {
this.style.backgroundColor = "rgb(174, 170, 170)";
}
a[i].onmouseleave = function () {
this.style.backgroundColor = "rgb(232, 225, 225)";
}
}
/************ Dont know what to do here **************/
var liDropdown = ul.getElementsByClassName("dropdown");
for (var i = 0; i < liDropdown.length; i++) {
liDropdown[i].style.display = "inline-block";
liDropdown[i].onmouseover = function () {
var ul = document.getElementById("navMainId"),
dropdown = ul.getElementsByClassName("dropdown-content");
for (var i = 0; i < dropdown.length; i++) {
dropdown[i].style.display = "block";
}
}
liDropdown[i].onmouseleave = function () {
var ul = document.getElementById("navMainId"),
dropdown = ul.getElementsByClassName("dropdown-content");
for (var i = 0; i < dropdown.length; i++) {
dropdown[i].style.display = "none";
}
}
}
var divDropCont = ul.getElementsByClassName("dropdown-content");
for (var i = 0; i < divDropCont.length; i++) {
divDropCont[i].style.display = "none";
divDropCont[i].style.position = "absolute";
divDropCont[i].style.backgroundColor = "#f9f9f9";
divDropCont[i].style.minWidth = "160px";
divDropCont[i].style.boxShadow = "0px 8px 16px 0px rgba(0,0,0,0.2)";
}
var aDropCont = ul.getElementsByClassName("menuSubName");
for (var i = 0; i < aDropCont.length; i++) {
aDropCont[i].style.color = "black";
aDropCont[i].style.padding = "12px 16px";
aDropCont[i].style.textDecoration = "none";
aDropCont[i].style.display = "block";
aDropCont[i].style.textAlign = "left";
aDropCont[i].onmouseover = function () {
this.style.backgroundColor = "rgb(174, 170, 170)";
}
aDropCont[i].onmouseleave = function () {
this.style.backgroundColor = "rgb(249, 249, 249)";
}
}
.dropdown-content{
display:none ! important;
}
a:hover+.dropdown-content{
display:block ! important;
}

How to make this memory board game work?

I am trying to make a memory board game. I got the css part of the game done, but how it the JavaScript part suppose to work out. I tried using the codes below. When I click on the box, even if they are the same, the box won't disappear and when it's not the same number, the box doesn't turn back. Also, for my "gamebox", I want to add a picture to be the background. I couldn't get it to work. Can anyone help me. Thanks.
<html>
<style>
#gamebox
{
position: absolute;
top: 100px;
left: 100px;
background-image: url("https://www.google.com/url?sa=i&rct=j&q=&esrc=s&source=images&cd=&cad=rja&uact=8&ved=&url=http%3A%2F%2Fwww.pokemontimes.it%2Fhome%2F2014%2F10%2Fannunciato-il-pokemon-center-mega-tokyo-in-apertura-a-dicembre%2F%3F%3Drelated&psig=AFQjCNFGPAm9tU9MR4AZJKe1s6F90F8UFg&ust=1454720806721506");
}
div.box
{
position: absolute;
background-color: red;
top: -800px;
left: -800px;
width: 100px;
height: 100px;
text-align: center;
font-size: 30px;
}
div.box:hover
{
background-color: blue;
}
</style>
<div id=gamebox></div>
<div id=boxdiv class=box onclick="clickedBox(this)"></div>
<script>
var squaresize = 100;
var numsquares = 6;
var numClicked = 0;
var firstClicked;
var secondClicked;
var game = [];
for (var i = 0; i < numsquares; i++)
{
game[i] = [];
for (var j = 0; j < numsquares; j++)
{
game[i][j] = Math.floor(Math.random()*5);
makeBox(i, j);
}
}
function theSame(abox, bbox)
{
var boxParts = abox.id.split("-");
var i = boxParts[1];
var j = boxParts[2];
var boxaNum = game[i][j];
var boxParts = bbox.id.split("-");
i = boxParts[1];
j = boxParts[2];
var boxbNum = game[i][j];
return(boxaNum == boxbNum);
}
function nextTurn()
{
if (numClicked != 2)
return;
if (theSame(firstClicked, secondClicked))
{
deleteBox(firstClicked);
deleteBox(secondClicked);
}
else
{
hideBox(firstClicked);
hideBox(secondClicked);
}
numClicked = 0;
}
function hideBox(box)
{
box.innerHTML = "";
box.style.backgroundColor = "red";
}
function deleteBox(box)
{
//really delete the box
box.style.backgroundColor = "";
}
function showBox(box)
{
var boxParts = box.id.split("-");
var i = boxParts[1];
var j = boxParts[2];
box.innerHTML = game[i][j];
box.style.backgroundColor = "black";
box.style.color = "white";
}
function clickedBox(box)
{
showBox(box);
numClicked++;
if (numClicked == 1)
{
firstClicked = box;
return;
}
if (numClicked == 2)
{
secondClicked = box;
}
}
function makeBox(i, j)
{
var boxdiv = document.getElementById("boxdiv");
var newBox = boxdiv.cloneNode(true);
newBox.style.left = i * (squaresize + 5);
newBox.style.top = j * (squaresize + 5);
newBox.style.width = squaresize;
newBox.style.height = squaresize;
newBox.id = 'box-' + i + '-' + j;
var gamebox = document.getElementById("gamebox");
gamebox.appendChild(newBox);
}
</script>
</html>
I think you're not calling nextTurn() anywhere in your code, meaning theSame() is never called, so nothing gets compared to eachother.
Maybe try calling nextTurn() when the numClicked === 2 in the clickedBox() function.

Categories