position: absolute isnt working with style.top and style.left - javascript

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

Related

HTML draw vertical line across whole div

I am trying to draw a vertical line across a whole div following the mouse. The problem is that other elements are over the line. I want the line go over all content.
Here is the fiddle: https://jsfiddle.net/9hzcm23q/
And here the code:
var element = document.getElementById('box');
var drawLines = function(event) {
var x = event.pageX;
var straightLine = element.querySelector('.straightLine');
var slTrans = 'translate(' + x + 'px, 0px)';
if(!straightLine) {
straightLine = document.createElement('div');
straightLine.classList.add('straightLine');
straightLine.style.height = "100%";
straightLine.style.width = '2px';
element.appendChild(straightLine);
}
straightLine.style.transform = slTrans;
}
element.addEventListener('mousemove', function(event) {
drawLines(event);
});
html, body{
height: 100%;
width: 100%;
margin: 0px;
}
.box {
height: 100%;
width: 100%;
background-color: white;
}
.straightLine {
z-index: 10;
position: fixed;
background-color: red;
}
<div class="box" id="box">
<h1>
Lorem
</h1>
<p>
dolor amet
</p>
</div>
You need to add top: 0 to straightLine class like below:
.straightLine {
z-index: 10;
position: fixed;
background-color: red;
top: 0;
}
Here is a working fiddle
You can append it as the first child of the element instead at the end.
var element = document.getElementById('box');
var drawLines = function(event) {
var x = event.pageX;
var straightLine = element.querySelector('.straightLine');
var slTrans = 'translate(' + x + 'px, 0px)';
if(!straightLine) {
straightLine = document.createElement('div');
straightLine.classList.add('straightLine');
straightLine.style.height = "100%";
straightLine.style.width = '2px';
element.insertBefore(straightLine, element.firstChild)
}
straightLine.style.transform = slTrans;
}
element.addEventListener('mousemove', function(event) {
drawLines(event);
});
html, body{
height: 100%;
width: 100%;
margin: 0px;
}
.box {
height: 100%;
width: 100%;
background-color: white;
}
.straightLine {
z-index: 10;
position: fixed;
background-color: red;
}
<div class="box" id="box">
<h1>
Lorem
</h1>
<p>
dolor amet
</p>
</div>

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>

How to move two different images across the screen using JavaScript

I have been challenged with a website that requires me to make two images race at random across the screen to a finish line. I am required to make this happen using JavaScript. Unfortunately I have ran into some trouble here making this happen.
I have the script that allows a div container and an object "animate" (which is a small square) to move across the screen to the right as I am supposed to do. My question comes into play when trying to do this to two different images.
The goal is to have the animation I have created to apply to the images, I cannot figure out how to apply the functions to the images already placed on the page to make it seem as if they are racing on random intervals across the page to the finish line.
I understand the concept of the animation and the JavaScript behind it, I just dont understand how to make it apply to an image, and more than 1 image at that.
Please advise.
Here is my code that I am using: you can see that I left my demo animation on the page, and the two images I am looking to apply it to.
function myMove()
{
var elem = document.getElementById("animate");
var pos = 0;
var id = setInterval(frame, 5);
function frame()
{
if (pos == 350)
{
clearInterval(id);
}
else
{
pos++;
elem.style.left = pos + 'px';
}
}
}
<div id="traffic-light">
<div id="stopLight" class="bulb"></div>
<div id="yeildLight" class="bulb"></div>
<div id="goLight" class="bulb"></div>
</div>
<style>
body {
overflow: hidden;
}
#bluefish {
position: absolute;
top: 31pc;
width: 17pc;
left: -.5pc;
}
#turtle {
position: absolute;
width: 15pc;
top: 20pc;
}
body {
background-image: url("http://www.hpud.org/wp-content/uploads/2015/08/WaterBackground2.jpg")
}
.finishline {
position: absolute;
right: -12pc;
top: 18pc;
}
#traffic-light {
height: 10pc;
width: 4pc;
background-color: #333;
border-radius: 20pc;
position: absolute;
}
.bulb {
height: 2pc;
width: 2pc;
background-color: #111;
border-radius: 50%;
margin: 15px auto;
transition: background 500ms;
}
#container {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}
#animate {
width: 50px;
height: 50px;
position: absolute;
background: red;
}
</style>
<img id="bluefish" src="http://clipartist.net/openclipart.org/2013/July/Blue_Fish_Goldfish.png">
<img id="turtle" src="http://www.clipartkid.com/images/386/turtle-free-stock-photo-illustration-of-a-green-sea-turtle-uPgZrm-clipart.png">
<img src="https://t1.rbxcdn.com/877010da8ce131dfcb3fa6a9b07fea89" class="finishline">
<p>
<button onclick="myMove()">Click Me</button>
</p>
<div id="container">
<div id="animate"></div>
</div>
Try this one:
function myMove()
{
var elemBluefish = document.getElementById("bluefish");
var elemBluefishWin = document.getElementById("bluefishwin");
var elemTurtle = document.getElementById("turtle");
var elemTurtleWin = document.getElementById("turtlewin");
var posBluefish = 0;
var posTurtle = 0;
var hasWinner = false;
elemBluefishWin.style.display = 'none';
elemTurtleWin.style.display = 'none';
var id = setInterval(frame, 5);
function frame()
{
if(posBluefish >= 350 && posTurtle >= 350)
{
clearInterval(id);
return;
}
if(posBluefish < 350)
{
posBluefish += Math.round(Math.random()*10);
if(posBluefish >= 350)
{
posBluefish = 350;
if(!hasWinner){
hasWinner = true;
elemBluefishWin.style.display = 'unset';
}
}
elemBluefish.style.left = posBluefish + 'px';
}
if(posTurtle < 350)
{
posTurtle += Math.round(Math.random()*10);
if(posTurtle >= 350)
{
posTurtle = 350;
if(!hasWinner){
hasWinner = true;
elemTurtleWin.style.display = 'unset';
}
}
elemTurtle.style.left = posTurtle + 'px';
}
}
}
<div id="traffic-light">
<div id="stopLight" class="bulb"></div>
<div id="yeildLight" class="bulb"></div>
<div id="goLight" class="bulb"></div>
</div>
<style>
body {
overflow: hidden;
}
#bluefish {
position: absolute;
top: 31pc;
width: 17pc;
left: -.5pc;
}
#turtle {
position: absolute;
width: 15pc;
top: 20pc;
}
#bluefishwin {
position: absolute;
right: 1pc;
top: 31pc;
display: none;
}
#turtlewin {
position: absolute;
right: 1pc;
top: 20pc;
display: none;
}
body {
background-image: url("http://www.hpud.org/wp-content/uploads/2015/08/WaterBackground2.jpg")
}
.finishline {
position: absolute;
right: -12pc;
top: 18pc;
}
#traffic-light {
height: 10pc;
width: 4pc;
background-color: #333;
border-radius: 20pc;
position: absolute;
}
.bulb {
height: 2pc;
width: 2pc;
background-color: #111;
border-radius: 50%;
margin: 15px auto;
transition: background 500ms;
}
/*#container {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}
#animate {
width: 50px;
height: 50px;
position: absolute;
background: red;
}*/
</style>
<img id="bluefish" src="http://clipartist.net/openclipart.org/2013/July/Blue_Fish_Goldfish.png">
<img id="turtle" src="http://www.clipartkid.com/images/386/turtle-free-stock-photo-illustration-of-a-green-sea-turtle-uPgZrm-clipart.png">
<img src="https://t1.rbxcdn.com/877010da8ce131dfcb3fa6a9b07fea89" class="finishline">
<img id="bluefishwin" src="http://a.dryicons.com/images/icon_sets/coquette_part_3_icons_set/png/128x128/prize_winner.png">
<img id="turtlewin" src="http://a.dryicons.com/images/icon_sets/coquette_part_3_icons_set/png/128x128/prize_winner.png">
<p>
<button onclick="myMove()">Click Me</button>
</p>
<div id="container">
<div id="animate"></div>
</div>
It gets an element for each image and adds every 5ms a random amount of pixels (between 0 and 9) to each pos of image.
If both "racers" reached the target (350px) the interval is cleared and the race is over.
The winner gets an image displayed at the finish line.
an example:
function startRace() {
animateRacer("player1", true);
animateRacer("player2", true);
}
function animateRacer(playerId, reset) {
var elem = document.getElementById(playerId);
var pos = parseInt(elem.style.left, 10);
if (isNaN(pos) || reset) {
pos = 0;
}
//console.log(playerId + ': ' + pos);
if (pos < 450) {
pos += randStep(3);
elem.style.left = pos + 'px';
setTimeout('animateRacer("' + playerId + '")', randStep(5));
}
}
function randStep(max) {
var min = 1;
return Math.floor(Math.random() * (max - min)) + min;
}
body {
overflow: hidden;
}
#container {
width: 500px;
height: 160px;
position: relative;
background-color: yellow;
}
.player {
width: 50px;
height: 50px;
background-color: gray;
position: relative;
}
#player1 {
background-color: red;
top: 20px;
}
#player2 {
background-color: blue;
top: 40px;
}
<p>
<button onclick="startRace()">Start Race</button>
</p>
<div id="container">
<div id="player1" class="player"></div>
<div id="player2" class="player"></div>
</div>
function mover(obj) {
this.obj=obj;
this.pos = 0;
this.id = setInterval(this.frame, 5);
}
mover.prototype.frame=function() {
if (this.pos == 350) {
clearInterval(this.id);
} else {
this.pos++;
this.obj.style.left = this.pos + 'px';
}
}
}
Simply do:
img1=new mover(document.getElementById("pic1"));
You can repeat this with every image and you could store them into an array:
images=[];
function letsmove(){
images.push(new mover(someid));
...
}
And you can do this with all images on the site:
images=[];
function letsmove(){
domimages=document.getElementsByTagName("img");
domimages.forEach(function(img){
images.push(new mover(img));
});
}
}
See JS OOP and JS Prototyping for more explanation

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>

Categories

Resources