How to make boxes disappear when clicked in javascript? - javascript

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>

Related

The square does not move JavaScript

I'm creating a game, the div with id "playerDiv" when I hit the space bar it should start going up but it doesn't. So I would like when I hit the space bar the div would go up high.
could you help me? could you also report me the mistakes i made?
const player = document.getElementById("playerDiv");
let inc = 0;
let playerTimeOut;
function jump() {
let x = 420 + inc;
player.top = player.top + x;
inc++
playerTimeOut = setTimeout(jump, 50);
}
window.addEventListener("keydown", checkKeyPress, false);
function checkKeyPress(key) {
if (key.key === ' ') {
jump();
}
}
body {
background-color: #222222;
}
#background {
border: solid 2px #dddddd;
width: 800px;
height: 500px;
}
#playerDiv {
background-color: #aaaaaa;
width: 60px;
height: 80px;
position: relative;
top: 420px;
left: 10px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="style.css" rel="stylesheet" type="text/css">
<title>Game</title>
</head>
<body>
<div id="background">
<div id="playerDiv">
</div>
</div>
</body>
<script src="script.js"></script>
</html>
You're not passing the argument in addListener and you're not using correctly the top property, it belongs to style and needs unit , for example px
Also keyCode is deprecated, use key instead
const player = document.getElementById("playerDiv");
let inc = 0;
let playerTimeOut;
function jump() {
let x = 10 + inc;
player.style.bottom = `${x}px`
inc++
console.log(player.style.bottom)
}
//window.addEventListener("keydown", e => e.key === "(Space Character)" ? jump() : '');
//For snippet only
jump()
setTimeout(() => jump(), 1000)
* {
/* demo */
box-sizing: border-box
}
body {
background-color: #222;
}
#background {
border: solid 2px #ddd;
width: 800px;
height: 500px;
position: relative;
/* demo */
max-width: 100%
}
#playerDiv {
background-color: #aaa;
width: 60px;
height: 80px;
position: absolute;
bottom: 0px;
left: 10px;
}
<div id="background">
<div id="playerDiv">
</div>
</div>
Try this:
const player = document.getElementById("playerDiv");
let inc = 0;
let playerTimeOut;
function jump() {
let x = 10 + inc;
let style = window.getComputedStyle(player);
player.style.top = (parseInt(style.getPropertyValue('top'),10) - x) + 'px';
inc++
}
window.addEventListener("keydown", checkKeyPress, false);
function checkKeyPress(key) {
if (key.keyCode == "32") {
jump();
}
}
body {
background-color: #222222;
}
#background {
border: solid 2px #dddddd;
width: 800px;
height: 500px;
}
#playerDiv {
background-color: #aaaaaa;
width: 60px;
height: 80px;
position: relative;
top: 420px;
left: 10px;
}
<div id="background">
<div id="playerDiv">
</div>
</div>

Collision or overlap - 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);
}

Javascript Math.random- Browser Doesn't Seem To Recognize Code

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>

Script works in jsfiddle but not HTML document

I have a script in jsfiddle that works: https://jsfiddle.net/oxw4e5yh/
However in HTML doc it is not working:
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
function calcSpeed(speed) {
// Time = Distance/Speed
var spanSelector = document.querySelectorAll('.marquee span'),
i;
for (i = 0; i < spanSelector.length; i++) {
var spanLength = spanSelector[i].offsetWidth,
timeTaken = spanLength / speed;
spanSelector[i].style.animationDuration = timeTaken + "s";
}
}
calcSpeed(75);
</script>
<style>
/* Make it a marquee */
.marquee {
width: 100%;
left: 0px;
height: 10%;
position: fixed;
margin: 0 auto;
white-space: nowrap;
overflow: hidden;
background-color: #000000;
bottom: 0px;
color: white;
font: 50px'Verdana';
}
.marquee span {
display: inline-block;
padding-left: 100%;
text-indent: 0;
animation: marquee linear infinite;
animation-delay: 5s;
background-color: #000000;
color: white;
bottom: 0px;
}
/* Make it move */
#keyframes marquee {
0% {
transform: translate(10%, 0);
}
100% {
transform: translate(-100%, 0);
}
}
/* Make it pretty */
.scroll {
padding-left: 1.5em;
position: fixed;
font: 50px'Verdana';
bottom: 0px;
color: white;
left: 0px;
height: 10%;
}
</style>
</head>
<body>
<div class="marquee">
<span>Lots of text, written in a long sentance to make it go off the screen. Well I hope it goes off the screen</span>
</div>
</body>
</html>
The script is a css and javascript marquee to control a steady speed for the scrolling text.
Any idea what I am missing?
Also, as you can see on the fiddle, it takes a while for the text to start scrolling. Can I reduce the delay?
Call your JS function once all the DOM is ready, usually this is being done by using window.onload as follows:
window.onload = function() {
calcSpeed(75);
}
You are trying to select an element that has not been created yet.
Move your script to below the marquee
<div class="marquee">
<span>Lots of text, written in a long sentance to make it go off the screen. Well I hope it goes off the screen</span>
</div>
<script type="text/javascript">
function calcSpeed(speed) {
// Time = Distance/Speed
var spanSelector = document.querySelectorAll('.marquee span'),
i;
for (i = 0; i < spanSelector.length; i++) {
var spanLength = spanSelector[i].offsetWidth,
timeTaken = spanLength / speed;
spanSelector[i].style.animationDuration = timeTaken + "s";
}
}
calcSpeed(75);
</script>
put your script and style codes before the closing of body.
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<div class="marquee">
<span>Lots of text, written in a long sentance to make it go off the screen. Well I hope it goes off the screen</span>
</div>
<script>
function calcSpeed(speed) {
// Time = Distance/Speed
var spanSelector = document.querySelectorAll('.marquee span'),
i;
for (i = 0; i < spanSelector.length; i++) {
var spanLength = spanSelector[i].offsetWidth,
timeTaken = spanLength / speed;
spanSelector[i].style.animationDuration = timeTaken + "s";
}
}
calcSpeed(75);
</script>
<style>
/* Make it a marquee */
.marquee {
width: 100%;
left: 0px;
height: 10%;
position: fixed;
margin: 0 auto;
white-space: nowrap;
overflow: hidden;
background-color: #000000;
bottom: 0px;
color: white;
font: 50px'Verdana';
}
.marquee span {
display: inline-block;
padding-left: 100%;
text-indent: 0;
animation: marquee linear infinite;
animation-delay: 5s;
background-color: #000000;
color: white;
bottom: 0px;
}
/* Make it move */
#keyframes marquee {
0% {
transform: translate(10%, 0);
}
100% {
transform: translate(-100%, 0);
}
}
/* Make it pretty */
.scroll {
padding-left: 1.5em;
position: fixed;
font: 50px'Verdana';
bottom: 0px;
color: white;
left: 0px;
height: 10%;
}</style>
</body>
</html>
this works on me
You should write all script in last of page because script will trying to find tag id's and DOM is not ready that time than give error.
Sample
<html>
<head>
<style>
/* your style here */
</style>
</head>
<body>
<!-- your html here -->
<script>
// your script here
</script>
</body>
</html>
Please read
JavaScript and CSS order
See this
function calcSpeed() {
// Time = Distance/Speed
var spanSelector = document.querySelectorAll('.marquee span'),
i;
for (i = 0; i < spanSelector.length; i++) {
var spanLength = spanSelector[i].offsetWidth,
timeTaken = spanLength / 1000;
spanSelector[i].style.animationDuration = timeTaken + "s";
}
//calcSpeed(10);
}
</script>
<body onload="calcSpeed()">
I tested it on Chrome and Firefox...works perfectly. So, I presume it should work for you too.

HTML Pong attemp not working

I have started a pong game where the guidelines have already been set for me but I have an issue with the ball. It is very early in development but I am stuck on this problem: The X axis will not move up and down. The ball is not meant to bounce off the paddles yet. Here is my code:
Index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Ping Pong</title>
<link href="pong.css" rel="stylesheet" type="text/css"/>
<script src="js/jquery.js" type="text/javascript"></script>
<script src="js/pong.js" type="text/javascript"></script>
</head>
<body>
<header>
<h1>Ping Pong</h1>
</header>
<!-- Scoreboard goes here -->
<div id="game">
<div id="playground">
<div id="ball"></div>
<div id="paddleA" class="paddle"></div>
<div id="paddleB" class="paddle"></div>
</div>
</div>
<!-- used for debugging -->
<div id="debug">
</div>
<footer>
This is an example of creating a Ping Pong Game.
</footer>
</body>
</html>
Pong.js
var KEY = {
UP:38,
DOWN:40,
W:87,
S:83
};
var directionX = 1;
var directionY = 1;
$(function(){
var timer = setInterval(gameloop,30)
});
//This is where the logic for the game goes.
function gameloop(){
var playground = $("#playground");
var ball = $("#ball");
var width = parseInt (playground.css("width"))
var left = parseInt (ball.css("left"));
if(left >= width){
directionX = -1;
}
else if (left <= 0){
directionX = 1;
}
var height = parseInt (playground.css("height"))
var top = parseInt (ball.css("top"));
if(top >= height){
directionY = -1;
}
else if (top <= 0){
directionY = 1;
}
ball.css("left",left+5 * directionX);
ball.css("top",height+5 * directionY);
}
function debug(text){
$("#debug").text(text);
}
And pong.css
#playground{
background: #e0ffe0 /*url(images/pixel_grid.jpg)*/;
width: 400px;
height: 200px;
position: relative;
overflow: hidden;
}
#ball {
background: #fbb;
position: absolute;
width: 20px;
height: 20px;
left: 150px;
top: 100px;
border-radius: 10px;
}
.paddle {
background: #bbf;
left: 50px;
top: 70px;
position: absolute;
width: 30px;
height: 70px;
}
#paddleB {
left: 320px;
}
#winner{
display:none;
position: relative;
width: 200px;
margin-left: 100px;
top: 30%;
font-size: 20px;
border: 3px solid red;
padding: 20px;
background-color: #FFF;
text-align:center;
font-family: Comic-Sans;
}
Oh and in case you were wondering, the js library was written for me.
You're using the height of the element instead of the offset (top).
It should be
ball.css("top", top + 5 * directionY);
I believe you need to use px when setting the CSS for top and left.
ball.css("left",(left+5 * directionX) + "px");
ball.css("top",(height+5 * directionY) + "px");

Categories

Resources