As you run the snippet you see the circle it just stays to the left
I'm thinking that I have the code where it should appear randomly
But I'm not sure what I'm doing wrong. Any ideas
What I've Done to Remedy?
I tried to review the code for spelling issues and errors, checked the console in browser inspect mode but it doesn't show that there is an issue.
// Start of Red Circle Function
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
var clickedTime;
var createdTime;
var reactionTime;
function makeBox() {
var time = Math.random();
time = time * 5000;
setTimeout(function() {
if (Math.random() > 0.5) {
document.getElementById("redCircle").style.borderRadius = "150px";
} else {
document.getElementById("redCircle").style.borderRadius = "10px";
}
var top = Math.random();
top = top * 300;
var left = Math.random();
left = left * 500;
document.getElementById("redCircle").style.top = top + "px";
document.getElementById("redCircle").style.left = left + "px";
document.getElementById("redCircle").style.backgroundColor = getRandomColor();
document.getElementById("redCircle").style.display = "block";
createdTime = Date.now();
}, time);
}
document.getElementById("redCircle").onclick = function() {
clickedTime = Date.now();
reactionTime = (clickedTime - createdTime) / 1000;
document.getElementById("time").innerHTML = reactionTime;
this.style.display = "none";
makeBox();
}
makeBox();
// End of Red Circle Function
body {
margin: 0px;
}
.header {
background-color: #E7F2F4;
margin: auto;
width: 98%;
text-align: center;
padding: 20px;
padding-bottom: 40px;
}
.header p {
font-size: 20px;
color: white;
}
.header h1 {
font-weight: 46px;
color: #0099CC;
}
#myButton {
background-color: #0099CC;
color: white;
}
body {
background-color: white;
}
/* Circle Button Start */
#redCircle {
background-color: red;
width: 150px;
height: 150px;
border-radius: 150px;
-moz-border-radius: 75px;
-webkit-border-radius: 75px;
display: none;
}
/* Circle Button Start */
<!DOCTYPE html>
<html>
<head>
<title>Javascript Reactor Game</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="header">
<h1>Javascript Reactor</h1>
<p>How Fast Can You Click On The Shapes?</p>
<button id="myButton">Click Here To Start The Reactor</button>
</div>
<center><b><p>Your Reaction Time:<span id="time"></p></b>
</center>
<br>
<!-- Circle Start -->
<button id="redCircle"></button>
<!-- Circle End -->
</script>
</body>
</html>
You need position: absolute; in the CSS for #redCircle so that the top and left styles will be used.
// Start of Red Circle Function
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
var clickedTime;
var createdTime;
var reactionTime;
function makeBox() {
var time = Math.random();
time = time * 5000;
setTimeout(function() {
if (Math.random() > 0.5) {
document.getElementById("redCircle").style.borderRadius = "150px";
} else {
document.getElementById("redCircle").style.borderRadius = "10px";
}
var top = Math.random();
top = top * 300;
var left = Math.random();
left = left * 500;
document.getElementById("redCircle").style.top = top + "px";
document.getElementById("redCircle").style.left = left + "px";
document.getElementById("redCircle").style.backgroundColor = getRandomColor();
document.getElementById("redCircle").style.display = "block";
createdTime = Date.now();
}, time);
}
document.getElementById("redCircle").onclick = function() {
clickedTime = Date.now();
reactionTime = (clickedTime - createdTime) / 1000;
document.getElementById("time").innerHTML = reactionTime;
this.style.display = "none";
makeBox();
}
makeBox();
// End of Red Circle Function
body {
margin: 0px;
}
.header {
background-color: #E7F2F4;
margin: auto;
width: 98%;
text-align: center;
padding: 20px;
padding-bottom: 40px;
}
.header p {
font-size: 20px;
color: white;
}
.header h1 {
font-weight: 46px;
color: #0099CC;
}
#myButton {
background-color: #0099CC;
color: white;
}
body {
background-color: white;
}
/* Circle Button Start */
#redCircle {
position: absolute;
background-color: red;
width: 150px;
height: 150px;
border-radius: 150px;
-moz-border-radius: 75px;
-webkit-border-radius: 75px;
display: none;
}
/* Circle Button Start */
<!DOCTYPE html>
<html>
<head>
<title>Javascript Reactor Game</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="header">
<h1>Javascript Reactor</h1>
<p>How Fast Can You Click On The Shapes?</p>
<button id="myButton">Click Here To Start The Reactor</button>
</div>
<center><b><p>Your Reaction Time:<span id="time"></p></b>
</center>
<br>
<!-- Circle Start -->
<button id="redCircle"></button>
<!-- Circle End -->
<script type="text/javascript" src="scripts.js"></script>
</body>
</html>
For the left and top style properties to have any effect, the element has to have a position other than static. The one you probably want is absolute. So add
position: absolute;
to your CSS rule for #redCircle.
// Start of Red Circle Function
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
var clickedTime;
var createdTime;
var reactionTime;
function makeBox() {
var time = Math.random();
time = time * 5000;
setTimeout(function() {
if (Math.random() > 0.5) {
document.getElementById("redCircle").style.borderRadius = "150px";
} else {
document.getElementById("redCircle").style.borderRadius = "10px";
}
var top = Math.random();
top = top * 300;
var left = Math.random();
left = left * 500;
document.getElementById("redCircle").style.top = top + "px";
document.getElementById("redCircle").style.left = left + "px";
document.getElementById("redCircle").style.backgroundColor = getRandomColor();
document.getElementById("redCircle").style.display = "block";
createdTime = Date.now();
}, time);
}
document.getElementById("redCircle").onclick = function() {
clickedTime = Date.now();
reactionTime = (clickedTime - createdTime) / 1000;
document.getElementById("time").innerHTML = reactionTime;
this.style.display = "none";
makeBox();
}
makeBox();
// End of Red Circle Function
body {
margin: 0px;
}
.header {
background-color: #E7F2F4;
margin: auto;
width: 98%;
text-align: center;
padding: 20px;
padding-bottom: 40px;
}
.header p {
font-size: 20px;
color: white;
}
.header h1 {
font-weight: 46px;
color: #0099CC;
}
#myButton {
background-color: #0099CC;
color: white;
}
body {
background-color: white;
}
/* Circle Button Start */
#redCircle {
background-color: red;
width: 150px;
height: 150px;
border-radius: 150px;
-moz-border-radius: 75px;
-webkit-border-radius: 75px;
display: none;
position: absolute;
}
/* Circle Button Start */
<!DOCTYPE html>
<html>
<head>
<title>Javascript Reactor Game</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="header">
<h1>Javascript Reactor</h1>
<p>How Fast Can You Click On The Shapes?</p>
<button id="myButton">Click Here To Start The Reactor</button>
</div>
<center><b><p>Your Reaction Time:<span id="time"></p></b>
</center>
<br>
<!-- Circle Start -->
<button id="redCircle"></button>
<!-- Circle End -->
</script>
</body>
</html>
Related
I have a button in my site which is a simple aim trainer and you should click the button with left click. Everything works like a charm but if you click the button and hold it, then you hold enter, you can click 303 times in 10secs and that is cheating. I want it to only be pressed with left click. Explain your answer please.
Link to the site: https://mfa-aim-trainer.netlify.app
var b = document.querySelector("button");
var score = document.getElementById('score');
var counter = 0;
var btn = document.getElementById("button");
var tensec = document.getElementById("10sec");
var pxs = document.getElementsByClassName('div');
var scr = document.getElementById("scr");
var mis = document.getElementById("mis");
var htm = document.getElementById("htm");
var missc = 0;
var height1 = 100;
var width1 = 100;
var theLeftSide = document.getElementById("theLeftSide");
var resetbtn = document.getElementById("reset");
var vr = document.getElementById("vr");
var hit = 1080;
var fontsize = 25;
var ulcls = document.getElementsByClassName("theul");
var ul = document.getElementById('10sec');
var best = document.getElementById("best");
var cntrspn = document.getElementsByClassName("cntrspn");
var lists = document.getElementsByClassName("lists");
b.addEventListener("click", change);
b.addEventListener("click", plus);
htm.addEventListener("click", miss);
pxs[0].addEventListener("click", plussize);
pxs[1].addEventListener("click", minesize);
theLeftSide.addEventListener("click", leftsclick);
b.addEventListener("click", misscmines);
resetbtn.addEventListener("click", resetall);
function plussize() {
height1 += 10;
width1 += 10;
missc++
missc + 1
missc--
fontsize += 3;
b.style.fontSize = fontsize + "px";
b.style.height = height1 + "px";
b.style.width = width1 + "px";
missc - 1;
}
function minesize() {
height1 -= 10;
width1 -= 10;
missc++
missc + 1
missc--
fontsize -= 3;
b.style.fontSize = fontsize + "px";
b.style.height = height1 + "px";
b.style.width = width1 + "px";
missc - 1;
}
function miss() {
missc++
mis.innerHTML = missc - counter;
}
setInterval(function() {
var misc = missc - counter;
ul.style.height = window.offsetheight;
var currscr = counter;
for (var i = 0; i < cntrspn.length; i += 1) {
if (parseInt(scr.textContent) > parseInt(best.textContent)) {
best.textContent = scr.textContent;
} else {
console.log("no new best");
}
}
mis.textContent = missc - counter;
ul.innerHTML += '<li class="lists">' + '<span class="cntrspn">' + counter + '</span>' + "-" + misc + '</li>';
missc = 0;
misc = 0;
counter = 0;
scr.textContent = counter;
mis.textContent = missc;
}, 10000);
function change() {
var i = Math.floor(Math.random() * 1500) + 1;
var j = Math.floor(Math.random() * 250) + 1;
var r = Math.floor(Math.random() * -1100) + 1;
b.style.padding = 0 + "px";
b.style.left = i + "px";
b.style.top = j + "px";
b.style.right = r + "px";
}
function plus() {
missc--
missc - 1
counter++;
scr.textContent = counter;
}
function leftsclick() {
missc--
missc - 1
}
function misscmines() {
missc++
missc + 1
}
function resetall() {
window.location.reload(true);
}
body {
margin: 0px;
padding: 0px;
}
.btn {
position: relative;
height: 125px;
width: 125px;
border-radius: 10px;
display: block;
background-color: whitesmoke;
font-size: 20px;
text-align: center;
user-select: none;
font-family: 'Roboto Mono', monospace;
}
.btn:hover {
background-color: #dcdcdc;
border-color: #dcdcdc;
}
.btndiv {
display: grid;
gap: 10px;
top: 5px;
left: 200px;
width: 1724px;
position: fixed;
user-select: none;
}
.sizes {
width: 80px;
height: auto;
color: white;
background-color: #2f2f2f;
cursor: pointer;
font-family: 'Roboto Mono', monospace;
font-size: 20px;
padding-left: 5px;
user-select: none;
}
.score {
font-family: 'Roboto Mono', monospace;
color: white;
font-size: 30px;
white-space: nowrap;
user-select: none
}
.shr7 {
font-size: 20px;
font-family: 'Roboto Mono', monospace;
left: 100px;
color: white;
left: 49%;
padding-left: 5px;
user-select: none
}
.allcont {
display: grid;
grid-template-columns: repeat(25, 1fr);
gap: 10px;
padding-left: 5px;
}
.theLeftSide {
width: 190px;
display: block;
height: 100vh;
background-color: #2f2f2f;
border-right: 6px solid #464646;
overflow-y: auto;
overflow-x: hidden;
}
.theul {
background-color: #2f2f2f;
color: white;
width: 150px;
margin-bottom: 0px;
font-family: 'Roboto Mono', monospace;
border-right: solid 6px #464646;
display: block;
}
li {
font-family: 'Roboto Mono', monospace;
font-size: 15px;
color: white;
user-select: none;
}
::-webkit-scrollbar {
width: 10px;
}
::-webkit-scrollbar-thumb {
border-radius: 10px;
background-color: #2a2a2a;
}
::-webkit-scrollbar-thumb:hover {
background-color: #252525;
}
<!DOCTYPE html>
<html id="htm" style="font-family: 'Roboto Mono', monospace; user-select: none;">
<head>
<meta charset="utf-8">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Roboto+Mono:wght#300&display=swap" rel="stylesheet">
<link rel="shortcut icon" type="image/png" href="icons\icon.png">
<link rel="stylesheet" type="text/css" href="aimcss.css">
<div class="btndiv"><button id="btn" class="btn"><b>Click me</b></button></div>
<div id="theLeftSide" class="theLeftSide">
<div id="pxs" class="sizes div">+ 10px</div>
<div id="pxs" class="sizes div">- 10px</div>
<div class="allcont">
<p id="score" class="score">score:
<p id="scr" class="score">0</p>
</p>
<title>Aim trainer</title>
</div>
<div class="allcont">
<p id="misses" class="score">misses:
<p id="mis" class="score">0</p>
</p>
</div>
<br onscroll="func()">
<div class="allcont" id="bestdiv">
<p class="score">Best:
<p class="score" id="best">0</p>
</p>
</div>
<br>
<div style=" padding-left: 5px;"><button style="height: 30px; width: 70px; font-size: 15px; font-family: 'Roboto Mono', monospace;" id="reset"><b>RESET</b></button></div>
<br><br>
<p type="inherit" class="shr7">• Score-Misses</p>
<ol start="1" id='10sec' class='theul'>
<li style="display: none;" class="lists"><span class="cntrspn">0</span>-0</li>
</ol>
</div>
</head>
<body id="bod" style="background-color: #181818;">
<script type="text/javascript" src="aimscript.js">
</script>
</body>
</html>
I recommend checking the event.pointerId variable when the click occurs.
b.addEventListener('click', change);
const change = (event) => {
if(event.pointerId === -1) {
// this is a "keyboard click" that you want to avoid
}
else {
// actual click
}
};
When the mouse is used, the pointerId should be non-negative. When the keyboard is used to "click," the ID will be -1.
If I understand correctly, you want to stop an edge case where users can hold down enter and the left mouse button as they will keep scoring.
I would recommend listening for the enter key using the keydown and keyup events to track when enter is pressed then using the state to disable any logic while it is pressed.
let isEnterPressed = false
window.addEventListener("keydown", e => {
if(e.keyCode === 13)
isEnterPressed = true // 13 is keycode for enter
})
window.addEventListener("keyup", e => {
if(e.keyCode === 13)
isEnterPressed = false // 13 is keycode for enter
})
then just use isEnterPressed to block any logic triggered by clicking.
This is just a simple example, you could generalize this to track any keyboard input
You can use keypress listener on the button and preventDefault() when the enter triggers on the button priventDefault() will stop that
var b = document.querySelector("button");
var score = document.getElementById('score');
var counter = 0;
var btn = document.getElementById("button");
var tensec = document.getElementById("10sec");
var pxs = document.getElementsByClassName('div');
var scr = document.getElementById("scr");
var mis = document.getElementById("mis");
var htm = document.getElementById("htm");
var missc = 0;
var height1 = 100;
var width1 = 100;
var theLeftSide = document.getElementById("theLeftSide");
var resetbtn = document.getElementById("reset");
var vr = document.getElementById("vr");
var hit = 1080;
var fontsize = 25;
var ulcls = document.getElementsByClassName("theul");
var ul = document.getElementById('10sec');
var best = document.getElementById("best");
var cntrspn = document.getElementsByClassName("cntrspn");
var lists = document.getElementsByClassName("lists");
b.addEventListener("click", change);
b.addEventListener("click", plus);
htm.addEventListener("click", miss);
pxs[0].addEventListener("click", plussize);
pxs[1].addEventListener("click", minesize);
theLeftSide.addEventListener("click", leftsclick);
b.addEventListener("click", misscmines);
resetbtn.addEventListener("click", resetall);
function plussize() {
height1 += 10;
width1 += 10;
missc++
missc + 1
missc--
fontsize += 3;
b.style.fontSize = fontsize + "px";
b.style.height = height1 + "px";
b.style.width = width1 + "px";
missc - 1;
}
function minesize() {
height1 -= 10;
width1 -= 10;
missc++
missc + 1
missc--
fontsize -= 3;
b.style.fontSize = fontsize + "px";
b.style.height = height1 + "px";
b.style.width = width1 + "px";
missc - 1;
}
function miss() {
missc++
mis.innerHTML = missc - counter;
}
setInterval(function() {
var misc = missc - counter;
ul.style.height = window.offsetheight;
var currscr = counter;
for (var i = 0; i < cntrspn.length; i += 1) {
if (parseInt(scr.textContent) > parseInt(best.textContent)) {
best.textContent = scr.textContent;
} else {
console.log("no new best");
}
}
mis.textContent = missc - counter;
ul.innerHTML += '<li class="lists">' + '<span class="cntrspn">' + counter + '</span>' + "-" + misc + '</li>';
missc = 0;
misc = 0;
counter = 0;
scr.textContent = counter;
mis.textContent = missc;
}, 10000);
function change(e) {
var i = Math.floor(Math.random() * 1500) + 1;
var j = Math.floor(Math.random() * 250) + 1;
var r = Math.floor(Math.random() * -1100) + 1;
b.style.padding = 0 + "px";
b.style.left = i + "px";
b.style.top = j + "px";
b.style.right = r + "px";
}
function plus() {
missc--
missc - 1
counter++;
scr.textContent = counter;
}
function leftsclick() {
missc--
missc - 1
}
function misscmines() {
missc++
missc + 1
}
function resetall() {
window.location.reload(true);
}
b.addEventListener("keypress", e => {
let key = e.keyCode || e.charCode;
if (key == 13) {
e.stopPropagation();
e.preventDefault();
}
})
body {
margin: 0px;
padding: 0px;
}
button{
outline: none;
}
.btn {
position: relative;
height: 125px;
width: 125px;
border-radius: 10px;
display: block;
background-color: whitesmoke;
font-size: 20px;
text-align: center;
user-select: none;
font-family: 'Roboto Mono', monospace;
}
.btn:hover {
background-color: #dcdcdc;
border-color: #dcdcdc;
}
.btndiv {
display: grid;
gap: 10px;
top: 5px;
left: 200px;
width: 1724px;
position: fixed;
user-select: none;
}
.sizes {
width: 80px;
height: auto;
color: white;
background-color: #2f2f2f;
cursor: pointer;
font-family: 'Roboto Mono', monospace;
font-size: 20px;
padding-left: 5px;
user-select: none;
}
.score {
font-family: 'Roboto Mono', monospace;
color: white;
font-size: 30px;
white-space: nowrap;
user-select: none
}
.shr7 {
font-size: 20px;
font-family: 'Roboto Mono', monospace;
left: 100px;
color: white;
left: 49%;
padding-left: 5px;
user-select: none
}
.allcont {
display: grid;
grid-template-columns: repeat(25, 1fr);
gap: 10px;
padding-left: 5px;
}
.theLeftSide {
width: 190px;
display: block;
height: 100vh;
background-color: #2f2f2f;
border-right: 6px solid #464646;
overflow-y: auto;
overflow-x: hidden;
}
.theul {
background-color: #2f2f2f;
color: white;
width: 150px;
margin-bottom: 0px;
font-family: 'Roboto Mono', monospace;
border-right: solid 6px #464646;
display: block;
}
li {
font-family: 'Roboto Mono', monospace;
font-size: 15px;
color: white;
user-select: none;
}
::-webkit-scrollbar {
width: 10px;
}
::-webkit-scrollbar-thumb {
border-radius: 10px;
background-color: #2a2a2a;
}
::-webkit-scrollbar-thumb:hover {
background-color: #252525;
}
<!DOCTYPE html>
<html id="htm" style="font-family: 'Roboto Mono', monospace; user-select: none;">
<head>
<meta charset="utf-8">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Roboto+Mono:wght#300&display=swap" rel="stylesheet">
<link rel="shortcut icon" type="image/png" href="icons\icon.png">
<link rel="stylesheet" type="text/css" href="aimcss.css">
<div class="btndiv"><button id="btn" class="btn"><b>Click me</b></button></div>
<div id="theLeftSide" class="theLeftSide">
<div id="pxs" class="sizes div">+ 10px</div>
<div id="pxs" class="sizes div">- 10px</div>
<div class="allcont">
<p id="score" class="score">score:
<p id="scr" class="score">0</p>
</p>
<title>Aim trainer</title>
</div>
<div class="allcont">
<p id="misses" class="score">misses:
<p id="mis" class="score">0</p>
</p>
</div>
<br onscroll="func()">
<div class="allcont" id="bestdiv">
<p class="score">Best:
<p class="score" id="best">0</p>
</p>
</div>
<br>
<div style=" padding-left: 5px;"><button style="height: 30px; width: 70px; font-size: 15px; font-family: 'Roboto Mono', monospace;" id="reset"><b>RESET</b></button></div>
<br><br>
<p type="inherit" class="shr7">• Score-Misses</p>
<ol start="1" id='10sec' class='theul'>
<li style="display: none;" class="lists"><span class="cntrspn">0</span>-0</li>
</ol>
</div>
</head>
<body id="bod" style="background-color: #181818;">
<script type="text/javascript" src="aimscript.js">
</script>
</body>
</html>
This is a color guessing game I'm working on. Basically it allows users to select a color out of six, and output correct if the color is the same as mentioned in the title or output try again if the color is wrong. When I try the first game, everything seems fine but when I select play again and select the colors again, an unexpected recursion occurs and I don't know where's the problem. Here is my code:
window.onload = () => {
"use strict";
let header = document.getElementsByTagName("header")[0];
let titleColor = document.getElementById("title_color");
let nav = document.getElementsByTagName("nav")[0];
let newColors = document.getElementById("new_colors");
let prompt = document.getElementById("prompt");
let easy = document.getElementById("easy");
let hard = document.getElementById("hard");
let active = document.getElementsByClassName("active")[0];
let colors = document.querySelectorAll("[id^=color]");
const initialize = () => {
let t = Math.floor(Math.random() * 5);
for (let i = 0; i < colors.length; i++) {
let r = Math.floor(Math.random() * 255);
let g = Math.floor(Math.random() * 255);
let b = Math.floor(Math.random() * 255);
colors[i].style.backgroundColor = `rgb(${r}, ${g}, ${b})`;
}
titleColor.innerHTML = colors[t].style.backgroundColor;
addingEventHandlers(t);
}
const addingEventHandlers = t => {
for (let i = 0; i < colors.length; i++) {
colors[i].addEventListener("click", () => {
console.log(i);
if (t === i) {
header.style.backgroundColor = colors[t].style.backgroundColor;
for (let j = 0; j < nav.children.length; j++) {
if (nav.children[j] === active) {
nav.children[j].style.color = "rgb(FF, FF, FF)";
nav.children[j].style.backgroundColor = colors[t].style.backgroundColor;
} else {
nav.children[j].style.color = colors[t].style.backgroundColor;
nav.children[j].style.backgroundColor = "rgb(FF, FF, FF)";
}
}
for (let j = 0; j < colors.length; j++) {
colors[j].style.backgroundColor = colors[t].style.backgroundColor;
}
prompt.innerHTML = "Correct";
newColors.innerHTML = "Play Again";
newColors.addEventListener("click", () => initialize())
} else {
console.log(i);
colors[i].style.transitionProperty = "background-color";
colors[i].style.transitionDuration = "1s";
colors[i].style.transitionTimingFunction = "ease-in-out";
colors[i].style.backgroundColor = "rgb(0, 0, 0)";
prompt.innerHTML = "Try Again";
newColors.innerHTML = "New Colors";
newColors.addEventListener("click", () => initialize())
}
})
}
}
initialize();
}
* {
box-sizing: border-box;
}
body {
margin: 0;
text-transform: uppercase;
font-family:'Courier New', Courier, monospace;
font-weight: normal;
font-size: 100%;
text-align: center;
}
header {
color: white;
background-color: navy;
margin: 0;
}
header>h3 {
font-size: 2em;
margin: 0;
}
header>h1 {
font-size: 4em;
margin: 0;
}
nav {
background-color: white;
color: navy;
position: relative;
height: 38px;
}
nav>button {
background-color: white;
color: navy;
border: none;
font-size: 1.5em;
padding: 5px;
text-transform: uppercase;
}
#new_colors {
position: absolute;
left: 20%;
}
#easy {
position: absolute;
left: 62%;
}
#hard {
position: absolute;
left: 72%;
}
nav>button:not(.active):hover {
cursor: pointer;
background-color: navy;
color: white;
}
button.active {
cursor: pointer;
background-color: navy;
color: white;
border: none;
}
#container {
background-color: black;
display: grid;
grid-gap: 20px;
align-content: center;
justify-content: center;
width: 100%;
height: 792px;
}
[id^=color] {
border-radius: 10px;
background-color: white;
width: 200px;
height: 200px;
}
[id^=color]:hover {
cursor: pointer;
opacity: 0.9;
}
#color1 {
grid-area: 1 / 1 / 2 / 2;
}
#color2 {
grid-area: 1 / 2 / 2 / 3;
}
#color3 {
grid-area: 1 / 3 / 2 / 4;
}
#color4 {
grid-area: 2 / 1 / 3 / 2;
}
#color5 {
grid-area: 2 / 2 / 3 / 3;
}
#color6 {
grid-area: 2 / 3 / 3 / 4;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="keywords" content="color guessing game">
<meta name="description" content="color guessing game">
<meta name="author" content="Nick">
<link rel="stylesheet" href="color_guessing.css">
<script src="color_guessing.js"></script>
</head>
<body>
<header>
<h3>The Great</h3>
<h1 id="title_color"></h1>
<h3>Guessing Game</h3>
</header>
<nav>
<button id="new_colors">New Colors</button>
<button id="prompt"></button>
<button id="easy" >Easy</button>
<button id="hard" class="active">Hard</button>
</nav>
<div id="container">
<div id="color1"></div>
<div id="color2"></div>
<div id="color3"></div>
<div id="color4"></div>
<div id="color5"></div>
<div id="color6"></div>
</div>
</body>
</html>
Just like #Thomas said in the comments you need to check if there is an event already and add an event listener if there is none.
if (!colors[i].onclick) {
// your add event listener code goes here
}
You call addingEventHandlers from within initialise. This means that when initialise is called again (like when you start a new game) you will call addEventListener on the same element a second time, meaning you will call a handler twice when the event occurs. And this only gets worse as you call initialise again and again.
So move the call to addingEventHandlers outside of the initialise function body, so that it only gets called on page load, and then no more.
So for my final assignment I have to create an interactive website using javascript, canvas, html, and css. So I made boxes for my javascript in my canvas and I want boxes to disappear when I click on them but I don't know how to do it. Can someone help me?
Here is my HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Assignment 5</title>
<link rel="stylesheet" href="css/index.css">
</head>
<body>
<header>
<h1>PART2 - JavaScript and The Canvas</h1>
</header>
<canvas id="canvas" width="1000" height="600"></canvas>
<script src="index.js" charset="utf-8"></script>
</body>
</html>
Here is my CSS:
html {
font-size: 14px;
}
header {
background-color: white;
height: 3rem;
text-align: center;
}
h1 {
color: black;
}
h2 {
color:white;
}
body{
background-color: white;
padding-left: 50px;
padding-right: 50px;
}
#canvas {
position: absolute;
top: 8rem;
left: 8rem;
width: 700px;
height: 400px;
background: white;
animation: move 8s ease infinite;
}
#keyframes move {
50% {
transform: translate(600px, 200px);
}
}
Here is my JavaScript
randomBoxes();
function getRandomColor() {
var color = '#';
for (var i = 0; i < 6; i++) {
color += (Math.random() * 17 | 0).toString(17);
}
return color;
}
function boundryNum(theMin, theMax) {
var theRange = (theMax - theMin) + 5;
var randomNum = Math.floor((Math.random() * theRange) + theMin);
return randomNum;
}
function drawbox() {
var width = Math.floor(Math.random() * 200) +20;
var height = Math.floor(Math.random() * 400) + 20;
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
context.fillRect(boundryNum(25,800),boundryNum(25,400),width,height);
context.fillStyle = getRandomColor();
}
function randomBoxes(){
var number = Math.floor(Math.random() * 5) + 1;
//Three to six times....
while(number >= 0) {
drawbox();
number--;
}
setInterval(drawbox, 2000)
}
You havn't included any code in your question so I have just made some, the way I understand your question
<div style="left: 30px; top: 30px; border-width: 3px; border-style: solid; border-color: black; width: 150px; height: 100px; display: ;" id="box1" onclick="disappear()">
<h3>Click me</h3>
</div>
<script type="text/javascript">
function disappear() {
document.getElementById("box1").style.display = "none" ;
}
</script>
I'm trying to make a gif img at the location my mouse clicked but for some reason the gif doesnt wanna go to the location i requested with style.top and style.left. Can someone help me?
here i try to create and place the gif img on a mouse click.
setInterval(checkCursor, 1);
function checkCursor(){
document.body.onclick = function(){
console.log(parseFloat(cursorX) + ', ' + cursorY);
var explo = document.createElement("img");
explo.src = "explosive.gif?" + new Date().getTime();
explo.style.position = "absolute";
explo.style.top = cursorY;
explo.style.left = cursorX;
explo.style.pointerEvents = "none";
document.body.appendChild(explo);
setTimeout(function(){explo.remove();}, 800);
}
}
here I search for the mouse location
var cursorX;
var cursorY;
document.onmousemove = function(e){
cursorX = e.pageX-100;
cursorY = e.pageY-100;
}
the -100 is to center the gif file on the mouse
this is all of the code:
<!DOCTYPE html>
<html>
<head>
<title> Menu </title>
<style>
#nav {
display: block;
position: fixed;
top: 0;
left: 0;
overflow-x: hidden;
transition: 0.5s;
background-color: grey;
color: black;
width: 0;
height: 100%;
}
nav a { text-decoration: none; cursor: pointer; display: block; color: white; padding-top: 5px; padding-bottom: 5px; padding-right: 50px; padding-left: 30px; }
nav a:hover { background-color: black; transition: 0.3s; }
#menu { transition: 0.3s; }
section { position: absolute; z-index: -1; width: 99%; height: 98%; }
#header {
background-color: red;
color: black;
text-align: center;
margin-left: 25%;
width: 50%;
}
</style>
</head>
<body bgcolor="black">
<video id="videoplayback" style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; pointer-events: none; opacity: 0.0;" src ="videoplayback.mp4" loop/></video>
<section id="body">
<nav id="nav">
<span id="menu">Menu</menu>
<a id="btncls"onclick="closeMenu()" style="float: right; padding: 5px; margin: 5px; font-size: 10px;">X</a>
<div style="top: 50px; position: fixed;" id="menu">
<a onclick="openIndex()">Home</a>
<a onclick="openClub()">Club</a>
Helenparkhurst
</div>
</nav>
<section id="index">
<header>
<button onclick="openMenu()">Open menu</button>
</header>
</section><section id="club">
<header>
<button onclick="openMenu()">Open menu</button>
</header><article>
<div id="choice" style="width: 100%; height: 100%;"><button onclick="join()">Join</button> | <button id="leave" onclick="leave()">Never</button></div>
<p id="header">
<span style="font-size: 32px">Welcome to the Megumin club !!!</span>
</p>
</article><footer>
</footer>
</section>
</section>
<script>
document.getElementById("menu").style.visibility = "hidden";
document.getElementById("club").style.visibility = "hidden";
function openIndex(){
document.getElementById("club").style.visibility = "hidden";
document.getElementById("index").style.visibility = "visible";
closeMenu();
}
function openClub(){
document.getElementById("index").style.visibility = "hidden";
document.getElementById("club").style.visibility = "visible";
closeMenu();
}
function openMenu(){
document.getElementById("nav").style.width = "17%";
document.getElementById("menu").style.opacity = "1.0";
document.getElementById("btncls").style.opacity = "1.0";
document.getElementById("menu").style.visibility = "visible";
}
function closeMenu(){
document.getElementById("nav").style.width = "0";
document.getElementById("menu").style.opacity = "0.0";
document.getElementById("btncls").style.opacity = "0.0";
setTimeout(function(){document.getElementById("menu").style.visibility = "hidden";}, 500);
}
var cursorX;
var cursorY;
document.onmousemove = function(e){
cursorX = e.pageX-100;
cursorY = e.pageY-100;
}
function join(){
var video = document.getElementById("videoplayback");
video.play();
document.getElementById('choice').remove();
setInterval(checkCursor, 1);
function checkCursor(){
document.body.onmouseup = function(){
console.log(parseFloat(cursorX) + ', ' + cursorY);
var explo = document.createElement("img");
explo.src = "explosive.gif?" + new Date().getTime();
explo.style.position = "absolute";
explo.style.top = cursorY;
explo.style.left = cursorX;
explo.style.pointerEvents = "none";
document.body.appendChild(explo);
setTimeout(function(){explo.remove();}, 800);
document.getElementById("videoplayback").style.opacity = "0.1";
setTimeout(function(){document.getElementById("videoplayback").style.opacity = "0.0";}, 1000);
}
}
}
function leave(){
document.getElementById("choice").style.position = "relative";
var rand1 = Math.floor(Math.random() * (600 - 30 + 1)) + 30;
document.getElementById("choice").style.top = rand1;
var rand2 = Math.floor(Math.random() * (1300 - 30 + 1)) + 30;
document.getElementById("choice").style.left = rand2;
console.log(rand1+', '+rand2);
}
</script>
</body>
</html>
You need to append px to the coordinates:
explo.style.top = cursorY + "px";
explo.style.left = cursorX + "px";
This looks like a CSS issue.
Add position: relative; to the body element.
body {
position: relative;
}
If your body element is empty, you'll also want to stretch it to the height of the window.
html,
body {
height: 100%;
}
I want to save and restore data from div - that is container of other divs,
In order to make it I use local storage and JSON like this:
window.onload = restoreJason;
function makeJson(){
var canvas = document.getElementById("canvas");
var shapes = canvas.querySelectorAll("div[class='drag']");
var divs = new Object();
for(var i=0; i<shapes.length; ++i){
divs[shapes[i].getAttribute('innerHTML')] = shapes[i].innerHTML;
}
localStorage.setItem("divs", JSON.stringify(divs));
}
function restoreJason(){
var divs = JSON.parse(localStorage.getItem("divs"));
var canvas = document.getElementById("canvas");
var shapes = canvas.querySelectorAll("div[class='drag']");
for(var i = 0; i<shapes.length; i++){
shapes[i].value = divs[shapes[i].getAttribute("innerHTML")];
}
console.log(divs);
}
However, I don't know how to access the innerHTML of the elements and save it or restore it.
What do you think I shall do?
(To be more detailed - I need to save the content of the div when user click on "save", and load it when the user click "load". This is a snippest of it...)
NOTICE: the "canvas" is just the id of the main div, and not a real "canvas".
function randomizeColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * letters.length)];
}
return color;
}
function randomizeRectangle() {
var width = Math.random() * 700 + 50;
var height = Math.random() * 250 + 50;
if (height <= 20) {
height = 20;
}
var posX = Math.round(Math.random() * window.innerWidth);
var posY = Math.round(Math.random() * window.innerHeight);
var randomRecObj = {
"width": width + "px",
"height": height + "px",
"posX": posX,
"posY": posY
};
return randomRecObj;
}
function makeShape() {
var rect = randomizeRectangle();
var rectDOM = document.createElement("div");
rectDOM.className = "rectangle";
rectDOM.style.border = "1px solid black";
rectDOM.style.width = rect.width;
rectDOM.style.height = rect.height;
rectDOM.style.background = randomizeColor();
rectDOM.style.top = rect.posY + "px";
rectDOM.style.left = rect.posX + "px";
//rectDOM.addEventListener("click", selectShape);
// rectDOM.style.transform =rect.rotation;
return rectDOM;
}
function randRect() {
var rectDOM = makeShape();
var canvas = document.getElementById("canvas");
canvas.appendChild(rectDOM);
}
function randOval() {
var ovalDOM = makeShape();
ovalDOM.style.borderRadius = "50%";
var canvas = document.getElementById("canvas");
canvas.appendChild(ovalDOM);
}
function changeColor(){
}
function cancelSelection() {
var selected = document.getElementsByClassName("selected");
while (selected) {
selected[0].classList.remove(selected[0]);
}
}
function removeShape(event) {
var selectedShapes = document.getElementsByClassName("selected");
var len = selectedShapes.length;
while (len > 0) {
selectedShapes[0].parentNode.removeChild(selectedShapes[0]);
--len;
}
}
function removeCorners(rectDom) {
var corners = document.getElementsByClassName("corners");
var len = corners.length;
while (len > 0) {
corners[0].classList.remove("corners");
--len;
}
}
.header{
background: #4ABDAC;
color: #fff;
margin: 1px;
}
hr{
border-top: 3px double #2a3132;
}
ul{
list-style: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #90afc5;
}
li{
float: left;
border: 2px solid #336b87;
padding: 3px;
margin: 3px;
}
li>a{
display: block;
color: #2a3132;
text-decoration: none;
padding: 10px 14px;
}
#color{
margin-left: 150px;
}
#rect{
margin-left: 100px;
}
li>a:hover{
color: #763626;
cursor: pointer;
}
#canvas{
background: #66a5ad;
position: relative;
height: 1200px;
width: 100%;
}
.corners{
position: absolute;
height: 10px;
width: 10px;
background:#fff;
border: 1px solid black;
display: none;
}
.selected .corners{
display: inline-block;
}
.cornerUpLeft{
top: -5px;
left: -5px;
}
.cornerUpRight{
top: -5px;
right: -5px;
}
.cornerBtmLeft{
bottom: -5px;
left: -5px;
}
.cornerBtmRight{
bottom: -5px;
right: -5px;
}
.rectangle{
position: absolute;
}
.colorBox{
border: 1px solid black;
height: 20px;
width: 20px;
list-style: none;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Sketch Board - Eyal Segal Project</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="css/style.css" rel="stylesheet">
<script src="js/sketch.js"></script>
</head>
<body>
<h1 class="header">Sketch Board</h1>
<div>
<ul class="toolbar">
<li><a>Load</a></li>
<li id="Save"><a>Save</a></li>
<li id="rect"><a onclick="randRect()">Rectangle</a></li>
<li><a onclick="randOval()">Oval</a></li>
</ul>
<hr>
</div>
<div class="canvas" id="canvas">
</div>
</body>
</html>
All you need to do is set the .innerHTML of the div id="canvas" into localStorage. There's no need for JSON or loops at all.
Also, don't use inline HTML event attributes (onclick). Instead, do all your JavaScript separately using modern, standards based event handling.
Lastly, there is no need for <a> elements to be able to respond to a click event. Actually, your a elements are invalid as they don't have a name or href attribute anyway. The li elements can simply be set up for click events.
This is the code to do it but it won't execute here in the Stack Overflow snippet environment, but you can see it working here.
// Get reference to the "canvas"
var can = document.getElementById("canvas");
// Save the content of the canvas to localStorage
function saveData(){
localStorage.setItem("canvas", can.innerHTML);
}
// Get localStorage data
function restoreData(){
can.innerHTML = localStorage.getItem("canvas");
}
// get load and save references
var load = document.getElementById("load");
var save = document.getElementById("save");
// Set up event handlers
load.addEventListener("click", restoreData);
save.addEventListener("click", saveData);
// Get references to the rect and oval "buttons" and set their event handlers
var rect = document.getElementById("rect");
rect.addEventListener("click", randRect);
var oval = document.getElementById("oval");
oval.addEventListener("click", randOval);
function randomizeColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * letters.length)];
}
return color;
}
function randomizeRectangle() {
var width = Math.random() * 700 + 50;
var height = Math.random() * 250 + 50;
if (height <= 20) {
height = 20;
}
var posX = Math.round(Math.random() * window.innerWidth);
var posY = Math.round(Math.random() * window.innerHeight);
var randomRecObj = {
"width": width + "px",
"height": height + "px",
"posX": posX,
"posY": posY
};
return randomRecObj;
}
function makeShape() {
var rect = randomizeRectangle();
var rectDOM = document.createElement("div");
rectDOM.className = "rectangle";
rectDOM.style.border = "1px solid black";
rectDOM.style.width = rect.width;
rectDOM.style.height = rect.height;
rectDOM.style.background = randomizeColor();
rectDOM.style.top = rect.posY + "px";
rectDOM.style.left = rect.posX + "px";
//rectDOM.addEventListener("click", selectShape);
// rectDOM.style.transform =rect.rotation;
return rectDOM;
}
function randRect() {
var rectDOM = makeShape();
var canvas = document.getElementById("canvas");
canvas.appendChild(rectDOM);
}
function randOval() {
var ovalDOM = makeShape();
ovalDOM.style.borderRadius = "50%";
var canvas = document.getElementById("canvas");
canvas.appendChild(ovalDOM);
}
function changeColor(){
}
function cancelSelection() {
var selected = document.getElementsByClassName("selected");
while (selected) {
selected[0].classList.remove(selected[0]);
}
}
function removeShape(event) {
var selectedShapes = document.getElementsByClassName("selected");
var len = selectedShapes.length;
while (len > 0) {
selectedShapes[0].parentNode.removeChild(selectedShapes[0]);
--len;
}
}
function removeCorners(rectDom) {
var corners = document.getElementsByClassName("corners");
var len = corners.length;
while (len > 0) {
corners[0].classList.remove("corners");
--len;
}
}
.header{
background: #4ABDAC;
color: #fff;
margin: 1px;
}
hr{
border-top: 3px double #2a3132;
}
ul{
list-style: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #90afc5;
}
li{
float: left;
border: 2px solid #336b87;
padding: 3px;
margin: 3px;
}
li>a{
display: block;
color: #2a3132;
text-decoration: none;
padding: 10px 14px;
}
#color{
margin-left: 150px;
}
#rect{
margin-left: 100px;
}
li>a:hover{
color: #763626;
cursor: pointer;
}
#canvas{
background: #66a5ad;
position: relative;
height: 1200px;
width: 100%;
}
.corners{
position: absolute;
height: 10px;
width: 10px;
background:#fff;
border: 1px solid black;
display: none;
}
.selected .corners{
display: inline-block;
}
.cornerUpLeft{
top: -5px;
left: -5px;
}
.cornerUpRight{
top: -5px;
right: -5px;
}
.cornerBtmLeft{
bottom: -5px;
left: -5px;
}
.cornerBtmRight{
bottom: -5px;
right: -5px;
}
.rectangle{
position: absolute;
}
.colorBox{
border: 1px solid black;
height: 20px;
width: 20px;
list-style: none;
}
<h1 class="header">Sketch Board</h1>
<div>
<ul class="toolbar">
<li id="load">Load</li>
<li id="save">Save</li>
<li id="rect">Rectangle</li>
<li id="oval">Oval</li>
</ul>
<hr>
</div>
<div class="canvas" id="canvas">
</div>