Collision or overlap - JavaScript - javascript

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);
}

Related

Change color of the div shown in the window

I'm trying to change the colors of the divs from skyblue to yellow, when a specific div appears OR goes through the middle of the window. I have been building my own logic which works fine when I scroll the page up and down slowly. But it doesn't work when I scroll the page fast. I have inserted a button which takes the page to the fourth div (Box - 5) from the 100 divs. When the fourth div appears the background color does not switch, I have the keep scrolling up and down for my logic to change the fourth background color. The button is placed at the bottom of the page.
So I need help in making a better logic to changing the div's background color when the div is at or goes through the middle of the window, no matter the page is being scrolled fast or slow OR the page being
directly shifted to a specific div. Thanks
My index.html:
window.onbeforeunload = function() {
this.scrollTo(0, 0);
}
var content = document.getElementById("content"),
current = 0;
for (var y = 0; y < 100; y++) {
var box = document.createElement("div");
box.id = "box";
box.innerHTML = "Box - " + (y + 1);
content.appendChild(box);
}
content.children[current].style.backgroundColor = "yellow";
window.onscroll = function() {
if (this.oldScroll > this.scrollY) {
if (current >= 1) {
var previous_box = content.children[current - 1];
if ((this.scrollY + this.innerHeight / 2) < previous_box.offsetTop + previous_box.clientHeight) {
content.children[current].style.backgroundColor = "skyblue";
current--;
content.children[current].style.backgroundColor = "yellow";
}
}
} else {
if (current < 99) {
var next_box = content.children[current + 1];
if ((this.scrollY + this.innerHeight / 2) > next_box.offsetTop) {
content.children[current].style.backgroundColor = "skyblue";
current++;
content.children[current].style.backgroundColor = "yellow";
}
}
}
this.oldScroll = this.scrollY;
}
document.querySelector("button").onclick = function() {
var y = content.children[4].offsetTop - (content.children[4].clientHeight / 4);
window.scrollTo(0, y);
};
body {
margin: 0;
}
#navigation {
min-width: 620px;
background-color: blue;
width: 100%;
height: 50px;
z-index: 1;
position: fixed;
top: 0;
}
#box {
position: relative;
height: 75%;
width: 100%;
margin: 15% auto 15% auto;
color: black;
background-color: skyblue;
border: black 1px solid;
font-size: 50px;
text-align: center;
}
button {
margin: 0% auto 15% auto;
left: 50%;
}
<div id="navigation"></div>
<div id="content"></div>
<button>GO TO BOX 5</button>
window.onbeforeunload = function() {
this.scrollTo(0, 0);
}
var content = document.getElementById("content"),
current = 0;
for (var y = 0; y < 100; y++) {
var box = document.createElement("div");
box.id = "box";
box.innerHTML = "Box - " + (y + 1);
content.appendChild(box);
}
content.children[current].style.backgroundColor = "yellow";
window.onscroll = function() {
for(var i=0;i<content.children.length;i++){
var top = content.children[i]. getBoundingClientRect().top;
var height = top+content.children[i].clientHeight;
var halfWindow = window.innerHeight*0.5;
if(top<halfWindow&&height>halfWindow){
content.children[i].style.backgroundColor = "skyblue";
}
else{
content.children[i].style.backgroundColor = "yellow";
}
}
}
document.querySelector("button").onclick = function() {
var y = content.children[4].offsetTop - (content.children[4].clientHeight / 4);
window.scrollTo(0, y);
};
body {
margin: 0;
}
#navigation {
min-width: 620px;
background-color: blue;
width: 100%;
height: 50px;
z-index: 1;
position: fixed;
top: 0;
}
#box {
position: relative;
height: 75%;
width: 100%;
margin: 15% auto 15% auto;
color: black;
background-color: skyblue;
border: black 1px solid;
font-size: 50px;
text-align: center;
}
button {
margin: 0% auto 15% auto;
left: 50%;
}
<div id="navigation"></div>
<div id="content"></div>
<button>GO TO BOX 5</button>

How to save innerHTML of div in a local storage?

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>

I want to move a object right side at a distance and after reaching that distance, it should move at its origin place again using javascript

//css part
.header2
{
height:20px;
width:1250px;
background-color:#000;
margin-left:50px;
margin-right:50px;
border-top-left-radius:50px;
border-top-right-radius:50px;
float:left;
position:relative;
}
#move1{
height:20px;
width:100px;
border-top-left-radius:50px;
border-top-right-radius:50px;
background-color:#00F;
position:absolute;
}
<html>
<body>
<div class="header2">
<div id="move1">
</div>
//javascript
<script>
function move(){
var elem = document.getElementById("move1");
var pos = 0;
var id = setInterval(frame,10);
function frame(){
if (pos == 1150)
//i add this part to reverse the object
{
elem.style.right = pos + 'px';
pos--;
}
else{pos++;
elem.style.left = pos + 'px';}}}
</script>
</body>
</html>
sorry i dont have any more details to write and other programmer can understand this code and my problem without describing more.
function move() {
var elem = document.getElementById("move1");
var container = document.getElementById("header");
var pos = 0;
var id = setInterval(frame, 10);
var direction = +1; // move right initially
var maxRight = container.offsetWidth - elem.offsetWidth; // turn around position
function frame() {
if (pos > maxRight || pos < 0) direction *= -1; // change direction
pos += direction;
elem.style.left = pos + 'px';
}
}
move();
.header2 {
height: 20px;
width: 250px;
background-color: #000;
margin-left: 50px;
margin-right: 50px;
border-top-left-radius: 50px;
border-top-right-radius: 50px;
float: left;
position: relative;
}
#move1 {
height: 20px;
width: 100px;
border-top-left-radius: 50px;
border-top-right-radius: 50px;
background-color: #00F;
position: absolute;
}
<div id="header" class="header2">
<div id="move1">
</div>
</div>

Smoke Trail Effect - Javascript

How can one make a smooth smoke trail effect with Javascript, out of the code I attached? The trail should follow an object, but have the position the object had a moment ago. The code I attached does have some sort of trail effect, but it is not smooth. Can give the trail a position using something like this: position:trail = position:object, 5 ms ago?
var left = parseInt(document.getElementById("thingy").style.left);
setInterval(fly, 10);
function fly() {
if (left > 300) {
left = 300;
};
left++;
document.getElementById("thingy").style.left = left + "px";
}
setInterval(trail, 100);
function trail() {
document.getElementById("trail").style.left = left + "px";
}
<div id="thingy" style="position:absolute; top:100px; left: 0px; width: 100px; height: 100px; background-color:#000000;"></div>
<div id="trail" style="position:absolute; top:125px; left: 0px; width: 50px; height: 50px; background-color:#CCCCCC; z-index: -10;"></div>
If it is possible I would like to stay out of jQuery.
This solution clones the element each time it moves.
CSS3 transitions are used on the cloned nodes' background to simulate a smoke trail.
The code ensures there are never more than 100 cloned nodes.
var thingy= document.getElementById('thingy'),
left = thingy.offsetLeft,
shadows= [],
delta= 4;
setInterval(fly, 10);
function fly() {
var shadow= thingy.cloneNode();
shadow.classList.add('shadow');
shadow.style.backgroundColor= 'silver';
document.body.appendChild(shadow);
setTimeout(function() {
shadow.style.backgroundColor= 'white';
},100);
shadows.push(shadow);
if(shadows.length>100) {
shadows[0].parentNode.removeChild(shadows[0]);
shadows.shift();
}
if(left+delta > document.body.offsetWidth-thingy.offsetWidth || left < 0) {
delta= -delta;
}
left+= delta;
thingy.style.left = left + 'px';
}
body {
margin: 0;
padding: 0;
}
#thingy {
position: absolute;
top: 100px;
left: 0px;
width: 100px;
height: 100px;
background-color: orange;
border-radius: 50%;
}
.shadow {
transition: all 1s;
z-index: -1;
}
<div id="thingy"></div>
Update
For a "smokier" effect, you can use random values for the cloned nodes' width, height, transition, etc., like I've done in this Snippet:
var thingy= document.getElementById('thingy'),
tleft = thingy.offsetLeft,
ttop = thingy.offsetTop,
smokes= [],
deltaX= deltaY= 2;
setInterval(fly, 10);
function fly() {
if(Math.random()>0.5) {
var smoke= thingy.cloneNode();
smoke.classList.add('smoke');
smoke.style.background= 'gray';
smoke.style.opacity= 0.2;
smoke.style.transition= Math.random()+'s';
smoke.style.width= Math.random()*thingy.offsetWidth+'px';
smoke.style.height= Math.random()*thingy.offsetHeight+'px';
smoke.style.marginTop= smoke.offsetHeight+'px';
smoke.style.borderRadius= (Math.random()*25+25)+'%';
document.body.appendChild(smoke);
setTimeout(function() {
smoke.style.opacity= 0;
},100);
smokes.push(smoke);
if(smokes.length>20) {
smokes[0].parentNode.removeChild(smokes[0]);
smokes.shift();
}
}
if(tleft+deltaX > document.body.offsetWidth-thingy.offsetWidth || tleft < 0) {
deltaX= -deltaX;
}
if(ttop +deltaY > document.body.offsetHeight-thingy.offsetHeight || ttop < 0) {
deltaY= -deltaY;
}
tleft+= deltaX;
ttop += deltaY;
thingy.style.left = tleft + 'px';
thingy.style.top = ttop + 'px';
}
body {
margin: 0;
padding: 0;
background: black;
height: 100vh;
}
#thingy {
position: absolute;
top: 100px;
left: 0px;
width: 100px;
height: 100px;
background-color: orange;
border-radius: 50%;
}
.smoke {
z-index: -1;
}
<div id="thingy"></div>

Why does HTML5 break this code?

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.

Categories

Resources