I wasn't sure how to ask this question in detail but why does this website not display properly when I set the document to <!DOCTYPE html>? I've tried this page on multiple browsers (ie, firefox, chrome, opera) and they all display incorrectly unless I omit the <!DOCTYPE html>. Here is the code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>DotSmasher</title>
<link rel="stylesheet" href="dotSmasher.css" type="text/css" />
<script type="text/javascript" src="dotSmasher.js"></script>
</head>
<body onload="setGameAreaBounds()" onresize="setGameAreaBounds()">
<div id="scoreLabel">Score: 0</div>
<div id="pageTitle">DotSmasher</div>
<div id="gameArea">
<button id="dot" onClick="detectHit()"></button>
</div>
</body>
</html>
Here is a screenshot of how it's suppose to look:
http://i.stack.imgur.com/TNTrQ.jpg
Here is a screenshot of how it looks after <!DOCTYPE html>:
http://i.stack.imgur.com/r5Qtm.jpg
The javascript and CSS codes are below:
var score = 0;
var aWidth;
var aHeight;
var timer;
function detectHit() {
score += 1;
scoreLabel.innerHTML = "Score: " + score;
}
function setGameAreaBounds() {
if (document.all) {
aWidth = document.body.clientWidth;
aHeight = document.body.clientHeight;
}
else {
aWidth = innerWidth;
aHeight = innerHeight;
}
aWidth -= 30;
aHeight -= 95;
document.getElementById("gameArea").style.width = aWidth;
document.getElementById("gameArea").style.height = aHeight;
aWidth -= 74;
aHeight -= 74;
moveDot();
}
function moveDot() {
var x = Math.floor(Math.random() * aWidth);
var y = Math.floor(Math.random() * aHeight);
if (x < 10)
x = 10;
if (y < 10)
y = 10;
document.getElementById("dot").style.left = x;
document.getElementById("dot").style.top = y;
clearTimeout(timer);
timer = setTimeout("moveDot()", 1000);
}
#scoreLabel {
font-family: Arial, Helvetica, sans-serif;
font-size: 14pt;
color: #000000;
font-weight: bold;
position: absolute;
top: 10px;
height: 25px;
}
#pageTitle {
font-family: Arial, Helvetica, sans-serif;
font-size: 24pt;
font-weight: bold;
color: #000099;
position: absolute;
top: 35px;
left: 10px;
height: 25px;
}
#gameArea {
position: absolute;
top: 75px;
left: 10px;
border: 1px solid #000000;
}
#dot {
position: absolute;
top: 25px;
left: 25px;
background-color: #000099;
width: 64px;
height: 64px;
}
#stop {
position: absolute;
top: 50px;
}
The problem is that the code you got from a college book is wrong. I found the book to be here.
At the moment there are at least 2 things wrong.
var x = Math.floor(Math.random() * aWidth);
var y = Math.floor(Math.random() * aHeight);
Both aWidth and aHeight are not initialized and therefore you are multiplying by a NULL. Set these to 1. Like this:
var aWidth = 1;
var aHeight = 1;
Also,
document.getElementById("dot").style.left = x;
document.getElementById("dot").style.top = y;
Should be:
document.getElementById("dot").style.left = x + "px";
document.getElementById("dot").style.top = y + "px";
They were missing the "px" on the end of the location.
And RobG is right it works without the DOCTYPE html because of the quirks mode of the browsers.
Hope this helps.
Related
this is my first question here. I am fairly new to html, css, and javascript.
What I wanted to achieve was similar to this mockup i've created:
my website mockup
I've tried to replace the rectangle on the left side with javascript code to achieve a similar effect. The javascript code was taken from this codepen:
https://codepen.io/vaaghu/pen/abmYGYz
I've nudged the canvas a bit to the right, but if i extend the canvas width and height, the canvas does extend, but the circle animations don't. How do I extend this animation?
var canvas = document.querySelector("canvas")
canvas.width = 800;
canvas.height = 1600;
var c = canvas.getContext("2d");
var mouse = {x:innerWidth/2,y:innerHeight/2}
window.addEventListener("mousemove",(event)=>{
mouse.x = event.x;
mouse.y = event.y;
})
window.addEventListener("resize",()=>{
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
int();
})
function Circle(x, y,dx,dy,radius,color) {
this.x = x;
this.y = y;
this.dx = dx;
this.dy = dy;
this.radius = radius;
this.color = color
var maxRadius = 30;
this.draw = function() {
c.beginPath();
c.arc(this.x,this.y,this.radius,0,Math.PI * 2,false);
c.fillStyle = color
c.fill();
}
this.update = function(){
if(this.x+this.radius > innerWidth || this.x-this.radius < 0) {
this.dx = -this.dx;
}
if(this.y+this.radius > innerHeight || this.y -this.radius < 0 ) {
this.dy = -this.dy;
}
if( mouse.x - this.x > -50 && mouse.x - this.x < 50 && mouse.y - this.y >-50 && mouse.y - this.y < 50) {
if (this.radius < maxRadius) {
this.radius += 1
}
} else {
if (this.radius > radius) {
this.radius -= 1
}
}
this.x += this.dx;
this.y += this.dy;
this.draw();
}
}
var colorArray = ["#F5871A","#81968F","#DFAA2F","#D76034","#F5411D"];
var circleArray = []
function int() {
circleArray = []
for (let i = 0; i < 700; i++) {
var x = Math.random() * window.innerWidth;
var y = Math.random() * (window.innerHeight ) ;
var radius = Math.random() * 5 + 2;
var dx = Math.random() - 0.5;
var dy = Math.random() - 0.5;
var color = colorArray[Math.floor(Math.random()*4)]
circleArray.push(new Circle(x,y,dx,dy,radius,color))
}
}
int()
function animate() {
requestAnimationFrame(animate);
c.clearRect(0,0,innerWidth,innerHeight)
for (let i = 0; i < circleArray.length; i++) {
circleArray[i].update()
}
}
animate();
.mediaViewInfo {
--web-view-name: Homepage;
--web-view-id: Homepage;
--web-scale-on-resize: true;
--web-show-navigation-controls: true;
--web-enable-deep-linking: true;
--web-page-font: arial, Manrope;
}
:root {
--web-view-ids: Homepage;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
border: none;
}
#Homepage {
position: absolute;
width: 100%;
height:450%;
font-family: arial, Manrope;
background-color: rgba(255,255,255,1);
overflow: hidden;
--web-view-name: Homepage;
--web-view-id: Homepage;
--web-scale-on-resize: true;
--web-show-navigation-controls: true;
--web-enable-deep-linking: true;
--web-page-font: arial;
}
canvas {
background: #FFFF05;
background-image: linear-gradient(to bottom, #81968F99, #FFE636CC, #FF000066);
margin: 50% 0% 0% 8%;
padding: 0vh 0vh 0vh 0vh;
z-index:-1;
width:auto;
}
#Wave_Vid {
position: absolute;
left: -19px;
top: -1920px;
width: 100vh;
height: 100vh;
overflow: hidden;
}
.Wave_container {
overflow: visible;
}
#MIDDLEcontainer {
position:absolute;
top: 24%;
left:59%;
}
#MIDDLE {
overflow: visible;
}
#Good_ideas_can_take_time {
line-height: 0.8;
width: 100%;
text-align: left;
padding-right: 10%;
font-family: Manrope, arial;
font-style: normal;
font-weight: bold;
font-size: 15vh;
color: rgba(129,150,143,1);
margin-bottom: 30px;
}
#And_execution_takes_even_more {
width: 100%;
line-height: 1em;
text-align: left;
padding-right: 30vh;
font-family: Manrope, arial;
font-style: normal;
font-weight: normal;
font-size: 5vh;
color: rgba(129,150,143,1);
margin-bottom: 20px;
}
#Line_ {
fill: transparent;
stroke: rgba(129,150,143,1);
stroke-width: 4px;
stroke-linejoin: miter;
stroke-linecap: butt;
stroke-miterlimit: 4;
shape-rendering: auto;
}
.Line_ {
width: 509px;
height: 10px;
transform: matrix(1,0,0,1,0,0);
margin-bottom: 40px;
}
#Midcontainer {
position:absolute;
}
#Mid {
float:bottom;
position:absolute;
}
.MySkills {
position: relative;
overflow:visible;
height: 1em;
text-align: left;
font-family: Manrope, arial;
font-style: normal;
font-weight: lighter;
font-size: 12vh;
color: rgba(129,150,143,1);
letter-spacing: -0.85px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>wbdg portfolio</title>
<link rel="stylesheet" type="text/css" id="applicationStylesheet" href="../faux styles.css"/>
</head>
<body>
<div>
<canvas></canvas>
<script id="jssomething" type="text/javascript" src="../faux scripts.js"></script>
<script src="https://kit.fontawesome.com/4f3ce16e3e.js" crossorigin="anonymous"></script>
<div id="MIDDLEcontainer">
<div id="MIDDLE">
<div id="Good_ideas_can_take_time">
<p>Good ideas can take time.</p>
</div>
<div id="And_execution_takes_even_more">
<span>And execution takes even more.</span>
</div>
<svg class="Line_" viewBox="0 0 674 4">
<path id="Line_" d="M 0 0 L 674 0">
</path>
</svg>
<div id="Midcontainer">
<div id="Mid">
<div class="MySkills"> Photos </div>
<div class="MySkills"> Illustrations </div>
<div class="MySkills"> Videos </div>
<div class="MySkills"> Animations </div>
<div class="MySkills"> Branding </div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
If I understand correctly, change these lines in int() function:
var x = Math.random() * window.innerWidth;
var y = Math.random() * (window.innerHeight ) ;
to this:
var x = Math.random() * canvas.width;
var y = Math.random() * canvas.height;
I'm trying to create a game where you control circle1 and make it go to circle2 and when this overlap happens there is an alert that says "Game Over".
I created a function that activates when the page loads and every 1000ms repeats the function, the problem is that as soon as I update the page, even if circle1 is not superimposed on circle2, it gives me an alert, and when I press ok, it opens another and so on...
Can you correct me? What am I doing wrong?
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Index</title>
<link href="style.css" rel="stylesheet" type="text/css">
<script src="script.js"></script>
</head>
<body onload="checkCollision()">
<div id="content"></div>
<div id="contentTwo"></div>
<div id="buttonDiv">
<button onclick="moveUp()" class="buttonUp">⇧</button>
<br>
<button onclick="moveLeft()">⇦</button>
<button onclick="moveDown()">⇩</button>
<button onclick="moveRight()">⇨</button>
</div>
</body>
</html>
CSS:
body {
background-color: #222222;
}
#content {
background-color: #aaaaaa;
width: 60px;
height: 60px;
position: relative;
border-radius: 50px;
left: 200px;
top: 20px;
}
#contentTwo {
background-color: #dddddd;
width: 40px;
height: 40px;
position: relative;
top: 80px;
border-radius: 50px;
}
button {
width: 50px;
height: 50px;
font-size: 30px;
font-weight: bold;
margin: auto;
}
.buttonUp {
margin-top: 300px;
}
#buttonDiv {
text-align: center;
width: auto;
height: auto;
background-color: transparent;
}
JavaScript:
var pixelTop = 20;
var pixelLeft = 200;
function checkCollision() {
if (document.getElementById("content").top === document.getElementById("contentTwo").top) {
alert("Game Over");
}
setTimeout("checkCollision()",1000);
}
function moveUp() {
pixelTop += -10;
document.getElementById("content").style.top = pixelTop+"px";
}
function moveLeft() {
pixelLeft += -10;
document.getElementById("content").style.left = pixelLeft+"px";
}
function moveDown() {
pixelTop += 10;
document.getElementById("content").style.top = pixelTop+"px";
}
function moveRight() {
pixelLeft += 10;
document.getElementById("content").style.left = pixelLeft+"px";
}
I want when circle1 is in the same position as circle2, a "Game Over" alert appears.
Snippet:
var pixelTop = 20;
var pixelLeft = 200;
function checkCollision() {
if (document.getElementById("content").top === document.getElementById("contentTwo").top) {
alert("Game Over");
}
setTimeout("checkCollision()", 1000);
}
function moveUp() {
pixelTop += -10;
document.getElementById("content").style.top = pixelTop + "px";
}
function moveLeft() {
pixelLeft += -10;
document.getElementById("content").style.left = pixelLeft + "px";
}
function moveDown() {
pixelTop += 10;
document.getElementById("content").style.top = pixelTop + "px";
}
function moveRight() {
pixelLeft += 10;
document.getElementById("content").style.left = pixelLeft + "px";
}
body {
background-color: #222222;
}
#content {
background-color: #aaaaaa;
width: 60px;
height: 60px;
position: relative;
border-radius: 50px;
left: 200px;
top: 20px;
}
#contentTwo {
background-color: #dddddd;
width: 40px;
height: 40px;
position: relative;
top: 80px;
border-radius: 50px;
}
button {
width: 50px;
height: 50px;
font-size: 30px;
font-weight: bold;
margin: auto;
}
.buttonUp {
margin-top: 300px;
}
#buttonDiv {
text-align: center;
width: auto;
height: auto;
background-color: transparent;
}
<body onload="checkCollision()">
<div id="content"></div>
<div id="contentTwo"></div>
<div id="buttonDiv">
<button onclick="moveUp()" class="buttonUp">⇧</button>
<br>
<button onclick="moveLeft()">⇦</button>
<button onclick="moveDown()">⇩</button>
<button onclick="moveRight()">⇨</button>
</div>
</body>
There are a few flaws in the way you're trying to achieve your goal here.
First of all, the reason it happens is that you're trying to access the 'top' css attribute incorrectly, therefore the result in undefined and equal for both sides of the condition:
document.getElementById("content").top // undefined
document.getElementById("contentTwo").top // undefined
Since both of them are undefined, they are equal. Instead, if you'd want to access the 'top' css attribute you'll need to use the following method:
getComputedStyle(document.getElementById("content")).top
You can read more here:
https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle
Second, there is an issue with the logic you're trying to implement, even in a case where the content top attribute would equal to contentTwo top attribute, that still doesn't mean that the 2 elements intersects.
Not sure if it's the best approach, but what I'd do instead is use the getBoundingClientRect method - https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect
That way you can get all the needed information(such as - x, y, width, height, left, right, bottom, top) in order to calculate whether the 2 circles intersects or not.
You should be able to calculate the distance between the 2 objects and then determine whether the 2 objects intersects or not, here is an example you can use for reference:
https://developer.mozilla.org/en-US/docs/Games/Techniques/2D_collision_detection
Last, I'd suggest trying to add logs in case you're having an unexpected scenario, by simply logging the result of the condition you could've easily seen that something is wrong there.
#pardovot
Yes i solved it, thanks a lot, this is the JavaScript code:
var pixelTop = 20;
var pixelLeft = 200;
function moveUp() {
pixelTop += -10;
document.getElementById("content").style.top = pixelTop+"px";
}
function moveLeft() {
pixelLeft += -10;
document.getElementById("content").style.left = pixelLeft+"px";
}
function moveDown() {
pixelTop += 10;
document.getElementById("content").style.top = pixelTop+"px";
}
function moveRight() {
pixelLeft += 10;
document.getElementById("content").style.left = pixelLeft+"px";
}
function checkCollision() {
var content1 = document.getElementById("content");
var position1 = content1.getBoundingClientRect();
var x1 = position1.left;
var y1 = position1.top;
var w1 = position1.width;
var h1 = position1.height;
var content2 = document.getElementById("contentTwo");
var position2 = content2.getBoundingClientRect();
var x2 = position2.left;
var y2 = position2.top;
var w2 = position2.width;
var h2 = position2.height;
if (x1 < x2 + w2 && x1 + w1 > x2 && y1 < y2 + h2 && y1 + h1 > y2) {
console.log("Hitted")
}
setTimeout("checkCollision()",1);
}
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 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>
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>