I'm trying to generate 100 random coloured boxes within the div with the existing by clicking generate button that has top and left position 0-400. Also if I hover over any coloured box it disappears until the last that will give me an alert last box with last box left.
I managed to create a box that generates different colours but im not sure how to generate a 100 let alone hover over and delete the boxes when it is, how would one go about doing that?
My HTML:
<!doctype html>
<html lang="en">
<head>
<title> Generator </title>
<meta charset="utf-8">
<script src="prototype.js"></script>
<script src="task4.js"></script>
<style>
#container {
height: 500px;
}
p {
width: 70px;
height: 70px;
background-color: rgb(100, 100, 255);
border: solid 2px black;
position: absolute;
}
</style>
</head>
<body>
<div id="container">
</div>
<button id="myButton"
onclick="createBoxes()"> Generate More
</button>
</body>
</html>
My JS
window.onload = function()
{
createBoxes();
}
function createBoxes()
{
var colors = ["red", "green", "blue", "purple", "yellow"];
var newP = document.createElement("p");
var top = 10 + "px";
var left = 10 + "px";
newP.style.top = top;
newP.style.left = left;
newP.style.backgroundColor = colors[ Math.floor( Math.random() *5 )];
$("container").appendChild(newP);
}
window.onload = function() {
createBoxes();
}
Let's get this done step by step.
While creating box element, you should not use p tag, div is the best choice here.
I have implemented as far as I understood from your question.
Let me know in the comments if I missed something.
I added comments in the code, check if you get it.
window.onload = function() {
createBoxes();
}
function createBoxes() {
var left = 0;
var top = 0;
var colors = ["red", "green", "blue", "purple", "yellow"];
// create a for loop and run 99 times;
for (var i = 1; i < 100; i++) {
var newDiv = document.createElement("div");
newDiv.classList.add('box')
newDiv.style.backgroundColor = colors[Math.floor(Math.random() * 5)];
newDiv.style.top = top + 'px';
newDiv.style.left = left + 'px';
// now add the event on this one;
newDiv.addEventListener('mouseover', removeBoxes);
$("#container").append(newDiv);
left += 70; // increase left 70px each time in the loop
if (i % 5 == 0) { // if the we have 5 boxes in one row, reset left to 0px and increase top property by 70px to get another row;
left = 0;
top += 70;
}
}
}
// function to remove the boxes on hover;
function removeBoxes() {
$(this).remove();
}
// add the mouseover event listener;
$('div.box').on('mouseover', removeBoxes);
#container {
min-height: 200px;
}
div.box {
width: 70px;
height: 70px;
background-color: rgb(100, 100, 255);
border: solid 2px black;
display: inline-block;
position: absolute;
box-sizing: border-box;
}
#myButton {
position: absolute;
right: 0;
top: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
</div>
<button id="myButton" onclick="createBoxes()"> Generate 99 More
</button>
Related
I made a basic javascript code so you can poke divs with you mouse.
Unfortunately I have to add them manualy but i wanna add so much of them with a pattern.
First i decided to use grid but i guessed it wont work because divs (which i call them squares from now on :D) can change their position.
So I was about to ask, how can I create a javascript code that i can spawn them until they fill the screen.
Also i have another question which is realted to this project, How can i make these squares just decors. I mean by decors i dont want them to effect the webside at all, when the blocks goes out of the screen the body starts to expend, is there any way to avoid that?
(Also it will be better if you make the snippet full screen!)
EDIT: I put the refresh-button on the top left on the main div so you can draw squares by clicking it!
let mouse = {
speedX: 0,
speedY: 0,
posX: 0,
posY: 0,
movement: 0,
speed: 0
}
//on mousemove update the moouse object
document.onmousemove = function(e) {
mouse.speedX = e.movementX;
mouse.speedY = e.movementY
mouse.posX = e.pageX;
mouse.posY = e.pageY;
}
//refresh the mouse movement and speed every 100ms
setInterval(() => {
mouse.movement =
Math.sqrt(Math.pow(mouse.speedX, 2) + Math.pow(mouse.speedY, 2));
mouse.speed = mouse.movement * 10;
}, 100);
//add a square div in parent element
function addSquare(parent) {
const newDiv = document.createElement("div");
newDiv.classList.add("square")
parent.appendChild(newDiv)
return newDiv;
}
//add squares in the parent element filling the available size
//gap is the space between squares, size is the edge of the square
//if skipbefore is false it will begin to draw the next square also if it won't fit entirely
function addSquares(parent, gap, size, skipbefore = true) {
const squares = [];
let rect = parent.getBoundingClientRect();
const availableWidth = rect.width;
const availableHeight = rect.height;
let top = 100;
while (top < availableHeight) {
let left = 0;
if (skipbefore && top + size > availableHeight)
break;
while (left < availableWidth) {
if (skipbefore && left + size > availableWidth)
break;
const square = addSquare(parent);
square.style.left = `${left}px`;
square.style.top = `${top}px`;
squares.push(square);
left += gap + size;
}
top += gap + size;
}
return squares;
}
//onmoveover event handler
const squareOnMouseOver = (event) => {
const element = event.target;
const y = mouse.speedY;
const x = mouse.speedX;
const rad = Math.atan2(y, x);
yAxis = mouse.movement * Math.sin(rad);
xAxis = mouse.movement * Math.cos(rad);
const rect = element.getBoundingClientRect();
const left = Math.round(rect.x + xAxis * 3);
const top = Math.round(rect.y + yAxis * 3);
element.style.left = `${left}px`;
element.style.top = `${top}px`;
const o = rad * (180 / Math.PI);
element.style.transform = `rotate(${o}deg)`;
}
//resets the .target parent and redraw the squares inside it
function drawSquares() {
const parent = document.querySelector('.target');
parent.innerHTML = '';
const squares = addSquares(parent, 25, 75);
const colors = [
'lightcoral',
'bisque',
'aquamarine',
'cadetblue',
'greenyellow',
'yellowgreen'
];
squares.forEach(square => {
const iColor = Math.floor(Math.random() * (colors.length - 1));
const color = colors[iColor];
square.style.background = color;
square.addEventListener('mouseover', squareOnMouseOver);
});
}
body{
margin: 0;
width: 100vw;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
background-color: rgb(242, 239, 231);
color: rgb(10, 10, 9);
}
.square{
background-color: lightcoral;
width: 75px;
height: 75px;
position: absolute;
transform: rotate(0deg);
transition: all ease-out 0.5s;
}
.background {
display: flex;
align-items: center;
justify-content: center;
width: 100%;
height: 100%;
}
.container .row .col > * {
display: inline-block;
}
.target {
display: block;
width: 100%;
height: 100%;
}
#draw {
font-size: 20px;
padding: .2em 1em;
cursor: pointer;
}
.name{
font-size: 40px;
}
#main-container{
position: absolute;
padding: 35px 45px;
width: 950px;
height: 285px;
box-shadow: 0px 2px 5px 2px rgb(191, 188, 182);
}
.links{
display: flex;
justify-content: center;
align-items: center;
}
.icons{
width: 55px;
height: auto;
margin: 0px 25px;
padding: 10px;
border-radius: 5px;
transition: all ease-in 0.2s;
}
.icons:hover{
background-color: rgb(144, 144, 144);
}
.refresh{
position: absolute;
}
.refresh-button{
width: 25px;
height: auto;
}
.btn:hover{
background-color: rgb(144, 144, 144);
}
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<link rel="stylesheet" href="css.css">
<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>Document</title>
</head>
<body>
<div class="background">
<div class="target"></div>
<div class="container text-center" id="main-container">
<div class="">
<div class="refresh">
<button class="btn" id="draw" onclick="drawSquares()"><img class="refresh-button" src="SVG/arrow-clockwise.svg"></button>
</div>
<div class="name">Berk Efe Keskin</div>
<br>
<i>This website is working in progress right now...</i>
<br>
<i>Here is some useful links.</i>
<br>
<br>
<div class="links">
<img class="icons" src="SVG/github.svg">
<img class="icons" src="SVG/linkedin.svg">
<img class="icons" src="SVG/stack-overflow.svg">
</div>
</div>
</div>
</div>
<script type="text/javascript" src = "javascript.js"></script>
</body>
</html>
You may have a function that given a container will be filled with how many squares can fit inside as long as there is still avaiable width and available height in the target.
Here in this demo I better factored your code and added a main function called drawSquares that gets called when the button reDRAW is clicked. Each time the squares are redrawn, the target content is emptied.
I'm using a button to trigger the box drawing because the available space depends on the size of the area when the action is fired. For example you can expand the snippet and decide to redraw the squares to have the whole new area filled again.
You may decide to call the action on document ready or when the window gets resized.
let mouse = {
speedX: 0,
speedY: 0,
posX: 0,
posY: 0,
movement: 0,
speed: 0
}
//on mousemove update the moouse object
document.onmousemove = function(e) {
mouse.speedX = e.movementX;
mouse.speedY = e.movementY
mouse.posX = e.pageX;
mouse.posY = e.pageY;
}
//refresh the mouse movement and speed every 100ms
setInterval(() => {
mouse.movement =
Math.sqrt(Math.pow(mouse.speedX, 2) + Math.pow(mouse.speedY, 2));
mouse.speed = mouse.movement * 10;
}, 100);
//add a square div in parent element
function addSquare(parent) {
const newDiv = document.createElement("div");
newDiv.classList.add("square")
parent.appendChild(newDiv)
return newDiv;
}
//add squares in the parent element filling the available size
//gap is the space between squares, size is the edge of the square
//if skipbefore is false it will begin to draw the next square also if it won't fit entirely
function addSquares(parent, gap, size, skipbefore = true) {
const squares = [];
let rect = parent.getBoundingClientRect();
const availableWidth = rect.width;
const availableHeight = rect.height;
let top = 100;
while (top < availableHeight) {
let left = 0;
if (skipbefore && top + size > availableHeight)
break;
while (left < availableWidth) {
if (skipbefore && left + size > availableWidth)
break;
const square = addSquare(parent);
square.style.left = `${left}px`;
square.style.top = `${top}px`;
squares.push(square);
left += gap + size;
}
top += gap + size;
}
return squares;
}
//onmoveover event handler
const squareOnMouseOver = (event) => {
const element = event.target;
const y = mouse.speedY;
const x = mouse.speedX;
const rad = Math.atan2(y, x);
yAxis = mouse.movement * Math.sin(rad);
xAxis = mouse.movement * Math.cos(rad);
const rect = element.getBoundingClientRect();
const left = Math.round(rect.x + xAxis * 3);
const top = Math.round(rect.y + yAxis * 3);
element.style.left = `${left}px`;
element.style.top = `${top}px`;
const o = rad * (180 / Math.PI);
element.style.transform = `rotate(${o}deg)`;
}
//resets the .target parent and redraw the squares inside it
function drawSquares() {
const parent = document.querySelector('.target');
parent.innerHTML = '';
const squares = addSquares(parent, 25, 75);
const colors = [
'lightcoral',
'bisque',
'aquamarine',
'cadetblue',
'greenyellow',
'yellowgreen'
];
squares.forEach(square => {
const iColor = Math.floor(Math.random() * (colors.length - 1));
const color = colors[iColor];
square.style.background = color;
square.addEventListener('mouseover', squareOnMouseOver);
});
}
body {
margin: 0;
width: 100vw;
height: 100vh;
display: flex;
}
.square {
background-color: lightcoral;
width: 75px;
height: 75px;
position: absolute;
transform: rotate(0deg);
transition: all ease-out 0.5s;
}
#Header {
font-size: italic;
}
.background {
width: 100%;
height: 100%;
}
.target {
position: relative;
display: block;
width: 100%;
height: 100%;
z-index: -1;
}
#draw {
font-size: 20px;
padding: .2em 1em;
cursor: pointer;
}
.container .row .col > * {
display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<link el="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<body>
<div class="background">
<span>Work in progress...</span>
<div class="container text-center">
<div class="row">
<div class="col">
<h1 id="Header">Work in progress...</h1>
<button id="draw" onclick="drawSquares()">reDRAW</button>
</div>
</div>
</div>
<div class="target"></div>
</div>
</body>
Here is my JSFiddle: https://jsfiddle.net/y6pnq7k5/3/
Sorry if it's too much code, I tried to narrow it down.
The main functions to look at are generatorClicked() and progressBarAnimation().
When you click on the boxes (for example fire spell tome), I have a progress bar animation that goes across the div. The problem is that if you spam click the div it will reset the progress bar back at the start, and because this is meant to be an idle game the progress bar should not be affected until it has finished it's job.
One solution I've tried are disabling pointer events via style:
var isClicked = true;
document.GetElementByID(this.id).style.pointerEvents = 'none';
//progress bar animation - after it's done isClicked = false
if(!isClicked) {
document.GetElementByID(this.id).style.pointerEvents = 'auto';
}
This had issues with either the progress bar not being clickable after the first progress bar finished, or it would still allow the click spam to reset the bar, depending on where I made isClicked false.
I've also tried creating a shield like the top answer in this post
Which just stopped the progress bar from moving at all.
I don't have any libraries, just vanilla JS. I know that my implementation of this progress bar animation is also dubious, but even if I refactor it I still would need the progress bar to not be affected by subsequent clicks as it will affect the gameplay.
pointer-events CSS property can be set to 'none' before the progress bar animation starts and reset to its original value after the progress bar animation stops.
var fireGenerators = ["fireSpellTome", "fireWizard", "fireTeacher", "fireSchool"];
var fireGeneratorStrings = ["Fire Spell Tome", "Fire Wizard", "Fire Teacher", "Fire School"];
var fireGeneratorAmount = new Array();
function initFireGenerators() {
for (i = 0; i < fireGenerators.length; i++) {
fireGeneratorAmount.push(0);
var div = document.createElement('div');
div.id = fireGenerators[i];
div.className = "fireGenerators";
div.innerHTML = fireGeneratorStrings[i];
div.onclick = generatorClicked;
var progressBar = document.createElement('div');
progressBar.id = fireGenerators[i] + "ProgressBar";
progressBar.className = "progressBar";
var amount = document.createElement('span');
amount.id = "amountFireGen" + i;
amount.class = "fireAmounts";
amount.innerHTML = "0";
div.appendChild(progressBar);
div.appendChild(amount);
main.appendChild(div);
}
}
function generatorClicked() {
console.log(this.id + " clicked");
progressBarAnimation(this.id);
}
function progressBarAnimation(parentID) {
const progressBarContainer = document.getElementById(parentID);
const progressBar = document.getElementById(parentID + "ProgressBar"); //Get progressBar div element
let id = null;
let currentWidth = 0; //Set the width to 0
clearInterval(id);
progressBarContainer.style.pointerEvents = "none";
id = setInterval(frame, 10); //TEMPORARY - Need to check what generator and match progress with speed
function frame() {
if (currentWidth == 330) {
clearInterval(id);
progressBar.style.width = "0px";
progressBarContainer.style.pointerEvents = "auto";
} else {
currentWidth++;
progressBar.style.width = currentWidth + "px";
}
}
return true;
}
initFireGenerators();
html, body {
height: 100%;
width: 100%;
margin: 0;
font-family: Arial, Helvetica, sans-serif;
user-select: none;
-webkit-user-select: none;
-moz-user-select: none;
-khtml-user-select: none;
-ms-user-select: none;
}
div span {
margin-left: 15px;
}
#main {
width: 100%;
height: 80%;
}
#fireSpellTome {
background-size: 100% 100%;
background-image: url('../images/firetome.png');
background-repeat: no-repeat;
}
.fireGenerators {
position: relative;
width: 330px;
height: 170px;
border:2px solid #000;
margin-top: 1px;
}
.progressBar {
position: absolute;
top: 0;
width: 0;
height: 100%;
background-color: #111;
opacity: 0.5;
}
.noPointers {
pointer-events: none;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="stylesheets/game.css">
</head>
<body>
<h1><span id="fireMagicAmount">0</span><br></h1>
<div id=main></div>
</body>
</html>
Do you remember that console video game "Guitar Hero"? Or if you are a little younger, "Piano Tiles"?
If you don't know what I'm talking about, click on this link to get an idea = https://www.youtube.com/watch?v=nWLKlEg0VMs&ab_channel=MattSterner
Well, that is exactly what I am doing with this website (on a more basic level of course).
THERE IS NO NEED TO READ THE WHOLE CODE...
What I need your help with:
Look into the JavaScript code and go to the animateFunction() function.
In the if statement you will see I wrote a condition that in human language would be "If I press 'Q key' and the square on the left is where it should be when you get the note right, then console.log(currentNotePosition.bottom);" and that if statement is the same for the notes on the middle line and on the right side.
The issue:
When I click on the keys ('Q', 'W', and 'E'), the console.log(currentNotePosition.bottom) does execute, but it does it sometimes and not when the note is on the spot it should be when I want it to console.log the bottom position. So basically, my code can't detect when a note is at the place where you can score a point.
My theory of the issue:
My code is not able to identify which div/musical_note exactly I want to "score on".
Here is a better place to see and play with my code (tap on the "create" button to start the "game"): https://codepen.io/xavi-font/pen/xxOedzK
(If on the Codepen playground you don't see the "web browser screen" then just pull it up from the bottom, it is a window just like the ones that "contain" the code).
PD: This is written in Vanilla JavaScrpt (No libraries or frameworks).
let speed = 1;
idArray = [];
let topPositionThatAdds = 0;
let squareLeft = {
color: "red",
positionLeft: "250px",
class: 'squareLeft',
}
let squareMiddle = {
color: "green",
positionLeft: "750px",
class: 'squareMiddle',
}
let squareRight = {
color: "yellow",
positionLeft: "1250px",
class: 'squareRight',
}
idList = 0;
randomSquare = [squareLeft, squareMiddle, squareRight];
function generateSquares() {
let randomValue = randomSquare[Math.floor(randomSquare.length * Math.random())];
const newDiv = document.createElement("div");
newDiv.classList.add(randomValue.class);
newDiv.style.top = "-100px";
newDiv.setAttribute("id", idList.toString());
idList++;
idArray.push(idList);
document.body.appendChild(newDiv);
for (let i = 0; i < idArray.length; i++) {
let element = document.getElementById(i.toString());
animateFunction(element);
}
}
function animateFunction(element) {
if (element.style.top == "-100px") {
const interval = setInterval(function() {
element.style.top = eval(parseInt(element.style.top) + 1).toString() + "px";
let currentNotePosition = element.getBoundingClientRect();
document.body.onkeyup = function(e) {
if (e.keyCode == 81 /*Q*/ && currentNotePosition.bottom > 700 && currentNotePosition.bottom < 900 && element.classList.contains('squareLeft')) {
console.log(currentNotePosition.bottom);
}else if (e.keyCode == 87 /*W*/ && currentNotePosition.bottom > 700 && currentNotePosition.bottom < 900 && element.classList.contains('squareMiddle')) {
console.log(currentNotePosition.bottom);
}else if (e.keyCode == 69 /*E*/ && currentNotePosition.bottom > 700 && currentNotePosition.bottom < 900 && element.classList.contains('squareRight')) {
console.log(currentNotePosition.bottom);
}
}
}, speed);
}
}
function startGame() {
let randomGenerationNumber = Math.floor(Math.random() * (500 - 250)) + 250;
const interval = setInterval(generateSquares, randomGenerationNumber);
}
document.getElementById('button').addEventListener("click", startGame);
body{
background: yellow;
padding: 0;
margin: 0;
overflow: hidden;
background-size: cover;
}
#bar{
position: absolute;
bottom: 0;
/* top: 770px; */
height: 100px;
width: 100%;
background: rgb(52,162,162);
background: linear-gradient(90deg, rgba(52,162,162,.25) 0%, rgba(144,28,103,1) 100%);
z-index: 2;
}
.squareRight{
position: absolute;
height: 100px;
width: 100px;
z-index: 1;
left: 250px;
background-size: cover;
background-color: red;
}
.squareMiddle{
position: absolute;
height: 100px;
width: 100px;
z-index: 1;
left: 750px;
background-size: cover;
background-color: green;
}
.squareLeft{
position: absolute;
height: 100px;
width: 100px;
z-index: 1;
left: 1250px;
background-size: cover;
background-color: blue;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>TapTap</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<button id="button">create</button>
<div id="bar"></div>
<script src="app.js"></script>
</body>
</html>
Thank you so much for your time, I hope you can help me with this since its been days and I still can't figure it out.
I have created a button which should shift the window's Y to "BOX - 5" div's Y middle through onclick. So in other words I want to set the "Box - 5" div in the middle of the window. I have tried many methods using window.scrollTo and using elements.innerHeight/2, but I still cannot center the element to the middle of the window/screen. Please Help.
I wish to only use Javascript, but if its not possible with it then I would accept jQuery script.
index.html:
window.onbeforeunload = function () {
this.scrollTo(0, 0);
}
var content = document.getElementById("content"),
current = 0;
for (var y=0;y<10;y++) {
var box = document.createElement("div");
box.id = "box";
box.innerHTML = "Box - " + (y+1);
content.appendChild(box);
}
document.querySelector("BUTTON").onclick = function() {
var box_5 = document.querySelectorAll("#box")[4];
/*
NEED HELP HERE
*/
}
body {
margin: 0;
}
#box {
position: relative;
height: 500px;
width: 100%;
margin: 5% auto 5% auto;
color: black;
background-color: skyblue;
border: black 1px solid;
font-size: 50px;
text-align: center;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<button>CLICK TO SET THE WINDOW'S Y MIDDLE TO (BOX 5)'s Y MIDDLE</button>
<div id="content"></div>
</body>
</html>
Updated your snippet as below. You can use DOM element property offsetTop to check its Y position and use window.scroll to scroll the view to that element. Another sidenote, it's better to not assign the same id to multiple elements, so I change the id property to class and added identifier _{index} for the class name.
window.onbeforeunload = function () {
this.scrollTo(0, 0);
}
var content = document.getElementById("content"),
current = 0;
for (var y=0;y<10;y++) {
var box = document.createElement("div");
box.className += "box _" + (y+1);
box.innerHTML = "Box - " + (y+1);
content.appendChild(box);
}
document.querySelector("BUTTON").onclick = function() {
var box_5 = document.querySelectorAll(".box._5")[0];
if (box_5) {
// scroll the window view to the element
window.scroll({
top: box_5.offsetTop,
behavior: 'smooth',
})
}
}
body {
margin: 0;
}
.box {
height: 500px;
width: 100%;
margin: 5% auto 5% auto;
color: black;
background-color: skyblue;
border: black 1px solid;
font-size: 50px;
text-align: center;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<button>CLICK TO SET THE WINDOW'S Y MIDDLE TO (BOX 5)'s Y MIDDLE</button>
<div id="content"></div>
</body>
</html>
I've made margin of 2 divs move (using variable and variable++ or -- with style attribute in js to change margin) Like that:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset="utf-8" />
<title>Game</title>
<style>
body{
position: absolute;
background: #f00;
}
.point{
position: absolute;
width: 15px;
height: 15px;
background: #fff;
border-radius: 10px;
margin: 0px 0 0;
}
.player{
position: absolute;
text-align: center;
width: 200px;
height: 20px;
background: #0005ff;
margin: 550px 550px 0px;
}
</style>
<script>
var num = 550;
$(document).keydown(function (event) {
switch (event.keyCode) {
// Left Arrow
case 37: num = num-- - 15;
document.getElementById('player').style.margin = '550px ' + num + 'px 0px';
break;
// Right Arrow
case 39: num = 15 + num++;
document.getElementById('player').style.margin = '550px ' + num + 'px 0px';
break;
}
});
var nump = 0;
$(document).load(function () {
nump++;
document.getElementById('point').style.margin = nump + 'px 0px 0px';
});
</script>
</head>
<body>
<div class="point" id="point"></div>
<div class="player" id="player"></div>
</body>
</html>
Now I got problem about moving div named point.The div, point is not moving when I use $(document).load but the other div works. How can I fix that?
My second question is how can i check when div "point" touch div "player" then i'll return div point to the start and make a loop.
try this to move the point
var nump = 0;
var touch = false;
var flagtouch;
$(document).ready(function () {
flagtouch = setInterval(function(){
movePoint(nump);
},1000);
});
function movePoint()
{
document.getElementById('point').style.margin = nump + 'px 0px 0px';
touch = chekTouch(); // check whether the divs touches and return true if touched
if(touch)
{
clearInterval(flagtouch);
}
else
{
nump = nump+5;
}
}
For the second question:
With http://api.jquery.com/position/, you can known the position of both divs, and as you know too the width and height of the elements, you can calculate the region occupied by each element, and then when the elements touch each other.