How to move multiple elements on mousemove - javascript

How can I use Javascript to select multiple elements and move them at the same time? I'm trying to make something like this without using jQuery: https://jenniferdewalt.com/caterpillar.html
// JavaScript source code
var container = document.getElementById("container");
//MAKE NEW DIV
//container.innerHTML = '<div id="circle" class="circle"></div>';
console.log(container.innerHTML);
var mouseX = 0;
var mouseY = 0;
var positionX = 0;
var positionY = 0;
var speed = 50;
var i;
var m = 0;
var newCircle;
//EVENTS / TRIGGERS
window.addEventListener("mousemove", mouseCoords);
setInterval(circlePosition, 30);
//Make Circles
makeCircles(20);
function makeCircles(num) {
for (i = 0; i < num; i++) {
container.innerHTML += '<div id="circle' + i + '" class="circle"></div> ';
//Circle with NEW ID
var newCircle = document.getElementById("circle" + i);
//This Circle Random Color;
var ranColor = genColor();
newCircle.style.backgroundColor = ranColor;
//This Circle Random Size;
var newSize = genSize();
newCircle.style.width = newSize + "px";
newCircle.style.height = newSize + "px";
}
}
console.log(container.innerHTML);
//FUNCTIONS.
//MOUSE COORDS
function mouseCoords(e) {
mouseX = e.clientX;
mouseY = e.clientY;
}
//CIRCLEPOSITION
function circlePosition() {
//Circle go's to Last Mouse position
var circleX = document.getElementById("circle0");
var circleY = document.getElementById("circle0");
positionX += (mouseX - positionX) / speed;
positionY += (mouseY - positionY) / speed;
circleX.style.left = positionX + "px";
circleY.style.top = positionY + "px";
}
// MOST IMPORTANT PART RELATED TO QUESTION
//Random Color
function genColor() {
var RGBarr = [];
for (c = 0; c < 3; c++) {
var newNum = Math.floor(Math.random() * 256);
RGBarr.push(newNum);
}
var newRGB = 'rgb(' + RGBarr[0] + ',' + RGBarr[1] + ',' + RGBarr[2] + ')';
return newRGB;
}
//Random Size
function genSize() {
var ranSize = Math.floor(Math.random() * 100) + 1;
return ranSize;
}
body {
background-color: black;
}
.circle {
position: absolute;
top: 0;
left: 0;
background-color: white;
width: 100px;
height: 100px;
border-radius: 50%;
}
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<link href="./HOWTOMOVEAFUCKINGCIRCLE.css" type="text/css" rel="stylesheet" />
<meta charset="utf-8" />
<title></title>
</head>
<body>
<div id="container"></div>
<!--Javscript-->
<script src="./HOWTOMOVEAFUCKINGCIRCLE.js"></script>
</body>
</html>
I'm Self taught so would really apreciate your help, if u can't be asked to help me with this project, please consider giving me some other example how i can move multiple elements at the same time. Greetings from the Netherlands.

Related

Can I snap this (blue) div on the highlighted square on the canvas?

When you drag the blue div, I'd like it to 'snap' into the middle of the green highlighted square when the mouse button is released. I cannot seem to find a way to read the coordinates from the box[] (Path2D()) interface. So is there a simple way to achieve this? Should I save the coordinates of the squares individually? Or can I somehow still get the points out of the Path2D interface?
const board = document.getElementById("board");
const ctxB = board.getContext("2d");
var Grid = false;
const boxsize = 64;
const amountOfrows = 8;
const amountOfHorBoxes = 7;
const totalAmountOfBoxes = amountOfrows * amountOfHorBoxes;
board.width = boxsize * 7.5;
board.height = boxsize * 8;
var addHorBox = 0;
var addVertBox = 0;
let boxes = [];
function drawGrid(){
Grid=true;
// for the amout of rows
for (let rowcount = 0; rowcount < amountOfrows; rowcount++) {
ctxB.lineWidth = 1;
ctxB.strokeStyle = "black";
ctxB.fillStyle = "white";
// filling the rows
if(rowcount%2==0){
for (let boxcount = 0; boxcount < amountOfHorBoxes; boxcount++) {
let box = new Path2D();
box.rect(addHorBox, addVertBox, boxsize, boxsize);
boxes.push(box);
ctxB.fill(box);
ctxB.stroke(box);
addHorBox+=boxsize;
}
}
addHorBox=0;
addVertBox+=boxsize;
}
}
MoveUnit(document.getElementById("unit"));
function MoveUnit(unit){
const rect = board.getBoundingClientRect();
const checkX = unit.clientWidth/2 - rect.left;
const checkY = unit.clientHeight/2 - rect.top;
var initialX;
var initialY;
var tile;
unit.onmousedown = mouseDown;
function mouseDown(e){
e = e || window.event;
e.preventDefault();
initialX = e.clientX;
initialY = e.clientY;
document.onmouseup = mouseUp;
document.onmousemove = moveMouse;
}
function moveMouse(e){
e = e || window.event;
e.preventDefault();
unit.style.top = (unit.offsetTop + e.clientY - initialY) + "px";
unit.style.left = (unit.offsetLeft + e.clientX - initialX) + "px";
boxes.forEach(box => {
if (ctxB.isPointInPath(box, unit.offsetLeft + checkX, unit.offsetTop + checkY)) {
ctxB.lineWidth = 2;
ctxB.fillStyle = 'green';
ctxB.fill(box);
ctxB.stroke(box);
tile=box;
}else{
ctxB.lineWidth = 1;
ctxB.strokeStyle = "black";
ctxB.fillStyle = 'white';
ctxB.fill(box);
ctxB.stroke(box);
}
});
// saving new mousepos after moving the unit
initialX = e.clientX;
initialY = e.clientY;
}
function mouseUp(){
document.onmousemove = false;
}
}
function loop(timestamp){
// draw once
if(Grid==false) drawGrid();
requestAnimationFrame(loop);
}
loop();
#board{
background-color: #999;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
#unit{
background-color: rgb(134, 162, 224);
position: absolute;
cursor: pointer;
z-index: 1;
width: 30px;
height: 30px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="testing.css"/>
<title>Gridding</title>
</head>
<body>
<div id="unit"></div>
<canvas id="board"></canvas></div>
<script src="testing.js"></script>
</body>
</html>
In those Path2D instances we can add some useful data that can do what you need:
let box = new Path2D();
box.rect(...
box.data = { row, column }
then on the function mouseUp we use that to 'snap' into the middle
unit.style.top = ((box.data.column + 0.5) * boxsize) + "px";
unit.style.left = ((box.data.row + 0.5) * boxsize) + "px";
I reduced a lot of your code on my example below, I'm focusing just on the question, you should do the same when asking questions, that helps others get to the point faster and gives you a better chance of a quick answer.
const board = document.getElementById("board");
const ctxB = board.getContext("2d");
const unit = document.getElementById("unit");
const boxsize = 32;
board.width = board.height = boxsize * 4;
let boxes = [];
for (let r = 0; r < 4; r++) {
for (let c = 0; c < 4; c++) {
let box = new Path2D();
box.rect(r * boxsize, c * boxsize, boxsize -0.5, boxsize -0.5);
box.data = { r, c }
boxes.push(box);
}
}
var position = { x: -1, y: -1 }
function mouseDown(e) {
document.onmouseup = mouseUp;
document.onmousemove = moveMouse;
position = { x: e.clientX, y: e.clientY}
}
function mouseUp() {
document.onmousemove = false;
boxes.forEach(box => {
if (ctxB.isPointInPath(box, position.x, position.y)) {
unit.style.top = ((box.data.c + 0.5) * boxsize) + "px";
unit.style.left = ((box.data.r + 0.5) * boxsize) + "px";
}
});
}
function moveMouse(e) {
unit.style.top = (unit.offsetTop + e.clientY - position.y) + "px";
unit.style.left = (unit.offsetLeft + e.clientX - position.x) + "px";
position = { x: e.clientX, y: e.clientY}
}
function loop(timestamp) {
ctxB.clearRect(0, 0, board.width, board.height)
boxes.forEach(box => {
ctxB.fillStyle = ctxB.isPointInPath(box, position.x, position.y)? 'green' : 'white'
ctxB.fill(box);
ctxB.stroke(box);
});
requestAnimationFrame(loop);
}
loop();
unit.onmousedown = mouseDown;
#unit {
background-color: blue;
position: absolute;
width: 20px;
height: 20px;
}
<canvas id="board"></canvas>
<br>
<div id="unit"></div>
In my code I'm separating the mouse events from the drawing,
we draw only on the loop.
the events change state variables.
Also noticed that in some cases two boxes got highlighted at the same time changing the size of the rect by a tiny bit fixed that boxsize -0.5

Alternative to element.getBoundingClientRect()

I have been using getBoundingClientRect(). At the beginning, I'm getting performance issues due to this. If I remove this method from my code, there is working well. Any alternatives to getBoundingClientRect() in javascript.
In this sample, I have created 2000 elements in button click and changed their positions in another button click. In that, I'm getting performance issues when using getBoundingClientRect().
Anyone help me to resolve this.
document.getElementById("click1").onclick = function() {
for (var i = 0; i < 2000; i++) {
var ele = document.createElement("DIV");
ele.id = i + '';
ele.className = "square";
ele.setAttribute("style", "position: absolute;left: 200px; top: 100px");
document.getElementById("marker").appendChild(ele);
}
};
document.getElementById("click").onclick = function() {
var markerCollection = document.getElementById("marker");
var width = 20,
height = 20;
var radius = width * 2;
var area = 2 * 3.14 * radius;
var totalMarker = 0;
var numberOfMarker = Math.round(area / width);
totalMarker += numberOfMarker;
var percent = Math.round((height / area) * 100);
percent =
markerCollection.children.length - 1 < numberOfMarker ?
100 / markerCollection.children.length - 1 :
percent;
var angle = (percent / 100) * 360;
var centerX = 200,
centerY = 100;
var count = 1;
var newAngle = 0,
first = false;
var dt1 = 0,
dt2 = 0;
dt1 = new Date().getTime();
for (var i = 0; i < markerCollection.children.length; i++) {
if (i != 1 && (i - 1) % totalMarker === 0) {
count++;
radius = (width + 10) * count;
newAngle = 0;
area = 2 * 3.14 * radius;
numberOfMarker = Math.round(area / width);
percent = Math.round((height / area) * 100);
angle = (percent / 100) * 360;
totalMarker += numberOfMarker;
}
var x1 = centerX + radius * Math.sin((Math.PI * 2 * newAngle) / 360);
var y1 = centerY + radius * Math.cos((Math.PI * 2 * newAngle) / 360);
var offset = markerCollection.children[i].getBoundingClientRect();
markerCollection.children[i]["style"].left = (x1 - (offset.width / 2)) + "px";
markerCollection.children[i]["style"].top = (y1 - (offset.height / 2)) + "px";
newAngle += angle;
}
dt2 = new Date().getTime();
alert(dt2 - dt1);
};
<!DOCTYPE html>
<html>
<head>
<style>
.square {
height: 20px;
width: 20px;
background-color: #555;
border: 1px solid red;
}
</style>
</head>
<body>
<button id="click1">Create Element</button>
<button id="click">Click To Change</button>
<div id='marker' style="width: 350px;height: 200px;border: 1px solid red">
</div>
</div>
<script>
</script>
</body>
</html>
If I'm not misreading your code, all you're using getBoundingClientRect() for is to calculate the width and height of an element you already know the width and height of (20x20px).
Just use your width and height variables directly, or possibly avoid having to do the offset calculation entirely, add transform: translate(-50% -50%) to the element's style.

How to have two different text elements moving randomly on a page in Javascript

So I've been reading this post which I found is the closest to what I want. Basically, I want two different text elements (two different words) moving around the page randomly and also bouncing off each other when they come in contact.
I have tried to edit the code so that it's black and have only one text element. However how can I also include a second text element (a different word) moving randomly as well?
Also how can I change it to Roboto Mono font?
// Return random RGB color string:
function randomColor() {
var hex = Math.floor(Math.random() * 0x1000000).toString(16);
return "#" + ("000000" + hex).slice(0);
}
// Poor man's box physics update for time step dt:
function doPhysics(boxes, width, height, dt) {
for (let i = 0; i < boxes.length; i++) {
var box = boxes[i];
// Update positions:
box.x += box.dx * dt;
box.y += box.dy * dt;
// Handle boundary collisions:
if (box.x < 0) {
box.x = 0;
box.dx = -box.dx;
} else if (box.x + box.width > width) {
box.x = width - box.width;
box.dx = -box.dx;
}
if (box.y < 0) {
box.y = 0;
box.dy = -box.dy;
} else if (box.y + box.height > height) {
box.y = height - box.height;
box.dy = -box.dy;
}
}
// Handle box collisions:
for (let i = 0; i < boxes.length; i++) {
for (let j = i + 1; j < boxes.length; j++) {
var box1 = boxes[i];
var box2 = boxes[j];
var dx = Math.abs(box1.x - box2.x);
var dy = Math.abs(box1.y - box2.y);
// Check for overlap:
if (2 * dx < (box1.width + box2.width ) &&
2 * dy < (box1.height + box2.height)) {
// Swap dx if moving towards each other:
if ((box1.x > box2.x) == (box1.dx < box2.dx)) {
var swap = box1.dx;
box1.dx = box2.dx;
box2.dx = swap;
}
// Swap dy if moving towards each other:
if ((box1.y > box2.y) == (box1.dy < box2.dy)) {
var swap = box1.dy;
box1.dy = box2.dy;
box2.dy = swap;
}
}
}
}
}
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
// Initialize random boxes:
var boxes = [];
for (var i = 0; i < 1; i++) {
var box = {
x: Math.floor(Math.random() * canvas.width),
y: Math.floor(Math.random() * canvas.height),
width: 50,
height: 20,
dx: (Math.random() - 0.5) * 0.3,
dy: (Math.random() - 0.5) * 0.3
};
boxes.push(box);
}
// Initialize random color and set up interval:
var color = randomColor();
setInterval(function() {
color = randomColor();
}, 450);
// Update physics at fixed rate:
var last = performance.now();
setInterval(function(time) {
var now = performance.now();
doPhysics(boxes, canvas.width, canvas.height, now - last);
last = now;
}, 50);
// Draw animation frames at optimal frame rate:
function draw(now) {
context.clearRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < boxes.length; i++) {
var box = boxes[i];
// Interpolate position:
var x = box.x + box.dx * (now - last);
var y = box.y + box.dy * (now - last);
context.beginPath();
context.fillStyle = color;
context.font = "40px 'Roboto Mono'";
context.textBaseline = "hanging";
context.fillText("motion", x, y);
context.closePath();
}
requestAnimationFrame(draw);
}
requestAnimationFrame(draw);
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
<!DOCTYPE html>
<html>
<body>
<head>
<link rel="stylesheet" href="test.css">
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
</head>
<canvas id="canvas"></canvas>
<script src="test.js"></script>
</body>
</html>
Multiple text boxes is easy :
Change the initialize boxes part to include more than one.
// Initialize random boxes:
var boxes = [];
var boxCount = 2
for (var i = 0; i < boxCount; i++) {
Second your random color is flawed , try this :
function randomColor() {
var hex = Math.floor(Math.random() * 0x1000000).toString(16);
return "#" + ("000000" + hex).substr(hex.length);
}
I don't think that roboto is available in the canvas element. (I could be wrong)
monospace is available though.
Edit
If you want different words you could use another array for them:
var words = ['motion','designer']
for (var i = 0; i < words.length; i++) {
as you create boxes use the words array.
You can't hard code the size of the box if you want have the words to collide. Height should be at least the font height 40px and if you want to get the width of the text box there is a context helping function :
box.width = context.measureText(words[i]).width;
See the snippet for usage :
// Return random RGB color string:
function randomColor() {
var hex = Math.floor(Math.random() * 0x1000000).toString(16);
return "#" + ("000000" + hex).substr(hex.length);
}
// Poor man's box physics update for time step dt:
function doPhysics(boxes, width, height, dt) {
for (let i = 0; i < boxes.length; i++) {
var box = boxes[i];
// Update positions:
box.x += box.dx * dt;
box.y += box.dy * dt;
// Handle boundary collisions:
if (box.x < 0) {
box.x = 0;
box.dx = -box.dx;
} else if (box.x + box.width > width) {
box.x = width - box.width;
box.dx = -box.dx;
}
if (box.y < 0) {
box.y = 0;
box.dy = -box.dy;
} else if (box.y + box.height > height) {
box.y = height - box.height;
box.dy = -box.dy;
}
}
// Handle box collisions:
for (let i = 0; i < boxes.length; i++) {
for (let j = i + 1; j < boxes.length; j++) {
var box1 = boxes[i];
var box2 = boxes[j];
var dx = Math.abs(box1.x - box2.x);
var dy = Math.abs(box1.y - box2.y);
// Check for overlap:
if (2 * dx < (box1.width + box2.width ) &&
2 * dy < (box1.height + box2.height)) {
// Swap dx if moving towards each other:
if ((box1.x > box2.x) == (box1.dx < box2.dx)) {
var swap = box1.dx;
box1.dx = box2.dx;
box2.dx = swap;
}
// Swap dy if moving towards each other:
if ((box1.y > box2.y) == (box1.dy < box2.dy)) {
var swap = box1.dy;
box1.dy = box2.dy;
box2.dy = swap;
}
}
}
}
}
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
// Initialize random boxes:
var boxes = [];
var words = ["designer","motion","hi"]
for (var i = 0; i < words.length; i++) {
var box = {
x: Math.floor(Math.random() * canvas.width),
y: Math.floor(Math.random() * canvas.height),
width: 50, // Will be dynamic
height: 42,
dx: (Math.random() - 0.5) * 0.3,
dy: (Math.random() - 0.5) * 0.3
};
boxes.push(box);
}
// Initialize random color and set up interval:
var color = randomColor();
setInterval(function() {
color = randomColor();
}, 450);
// Update physics at fixed rate:
var last = performance.now();
setInterval(function(time) {
var now = performance.now();
doPhysics(boxes, canvas.width, canvas.height, now - last);
last = now;
}, 50);
// Draw animation frames at optimal frame rate:
function draw(now) {
context.clearRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < boxes.length; i++) {
var box = boxes[i];
// Interpolate position:
var x = box.x + box.dx * (now - last);
var y = box.y + box.dy * (now - last);
box.width = context.measureText(words[i]).width;
context.beginPath();
context.fillStyle = color;
context.font = "normal 40px monospace";
context.textBaseline = "hanging";
context.fillText(words[i], x, y);
context.closePath();
}
requestAnimationFrame(draw);
}
requestAnimationFrame(draw);
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
<!DOCTYPE html>
<html>
<body>
<head>
<link rel="stylesheet" href="test.css">
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
</head>
<canvas id="canvas"></canvas>
<script src="test.js"></script>
</body>
</html>

Pan and Zoom (on mouse-wheel) based on cursor location

The purpose of my code is to be able to pan and zoom a div element. It works perfectly fine except that the zooming is done from the center (which is normal). I need the div to zoom based on the cursor location (kind of like google maps zoom works) so I used transform-origin to shift the zoom from the center to the cursor's location. It works totally fine, except that whenever I change the mouse position to zoom again, the div element 'jumps' a few pixels and after this 'jump' it works (zoom and panning) perfectly fine again.
I think the reason is that I am not calculating the new distances correctly (after zooming) since the origin of the div changes.
Anyone can help on this one please?
NB: If I zoom out then zoom in to the exact same scale, there will be no 'jump'.
You can have a look at my code here in case I wasn't clear enough:
window.onload = function () {
initializeImage();
};
function initializeImage() {
var recElements = document.getElementsByClassName("rec");
var rec = recElements[0];
rec.panning = {};
rec.imageZoom = 100;
rec.stoprecMove = function () {
this.panning.xMouseDown = null;
this.panning.yMouseDownn = null;
};
rec.recMove = function() {
var dx = 0;
var dy = 0;
var scale = this.imageZoom * 0.01;
var pos = this.getBoundingClientRect();
dx = (this.panning.xMove - this.panning.xMouseDown) / scale;
dy = (this.panning.yMove - this.panning.yMouseDown) / scale;
dx = startOffsetX + dx;
dy = startOffsetY + dy;
var xZoom = this.xZoom;
var yZoom = this.yZoom;
var xTransform = xZoom - dx;
var yTransform = yZoom - dy;
var dxInPixel = dx + "px";
var dyInPixel = dy + "px";
this.style.transform = "translate(" + dxInPixel + "," + dyInPixel + ")" + "scale(" + scale + ")";
this.style.transformOrigin = xTransform + "px" + " " + yTransform + "px";
this.lastX = dx;
this.lastY = dy;
};
rec.onmousewheel = function (e) {
this.panning.xMove = 0;
this.panning.yMove = 0;
this.panning.xMouseDown = 0;
this.panning.yMouseDown = 0;
this.xZoom = e.clientX;
this.yZoom = e.clientY;
if (typeof this.lastX === "undefined") {
startOffsetX = 0;
startOffsetY = 0;
}
else {
startOffsetX = this.lastX;
startOffsetY = this.lastY;
}
var zoom = rec.imageZoom;
var delta = event.detail ? event.detail * -120 : event.wheelDelta;
zoom += delta / 15;
if (zoom > 300) zoom = 300; else if (zoom < 30) zoom = 30;
rec.imageZoom = zoom;
this.recMove();
};
rec.onmousedown = function (e) {
var xMouseDown = e.clientX;
var yMouseDown = e.clientY;
console.log("x: " + xMouseDown + " y: " + yMouseDown);
this.panning.xMouseDown = xMouseDown;
this.panning.yMouseDown = yMouseDown;
if (typeof this.lastX === "undefined") {
startOffsetX = 0;
startOffsetY = 0;
}
else {
startOffsetX = this.lastX;
startOffsetY = this.lastY;
}
e.preventDefault();
};
rec.onmousemove = function (e) {
if (this.panning.xMouseDown && this.panning.yMouseDown) {
this.panning.xMove = e.clientX;
this.panning.yMove = e.clientY;
this.recMove();
e.preventDefault();
}
};
rec.onmouseup = function () {
this.stoprecMove();
};
rec.onmouseout = function () {
this.stoprecMove();
};
}
.rec {
width: 200px;
height: 100px;
background-image: repeating-linear-gradient(to right, yellow, gray 10%, green 15%, yellow 30%, gray 40%, green 45%, yellow 60%, gray 70%, green 75%, yellow 90%, gray 100%);
position: fixed;
top: 0;
left: 0;
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<script src="script.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="styles.css"/>
</head>
<body>
<div class = "rec"></div>
</body>
</html>

Invalid assignment and onload problems in javascript/html

I'm very new to HTML, CSS, and Javascript. So while I've been having trouble with some of the errors. Here's my code so far
<!doctype html>
<html>
<head>
<style>
div {position: absolute};
</style>
<script type="text/javascript">
function pattern() {
var the_body = getElementById("theBody");
var xPos = 25;
var yPos = 25;
var width = 300;
var height = 300;
while (xPos <= 105) {
var newDiv = docoument.createElement("div");
newDiv.style.left = xPos;
newDiv.style.top = yPos;
newDiv.width = width;
newDiv.height = height;
var randR = Math.floor(Math.random()*255);
var randG = Math.floor(Math.random()*255);
var randB = Math.floor(Math.random()*255);
newDiv.background-color = rgb(randR, randG, randB);
the_body.appendChild(newDiv);
xPos += 10;
yPos += 10;
width -= 20;
height -= 20;
}
}
</script>
</head>
<body id="theBody" onload="pattern()">
</body>
</html>
This code will generate a series of squares on top of each other that get progressively smaller. It will assign each a different background color. However, I'm getting the following errors
Uncaught ReferenceError: Invalid left-hand side in assignment
newDiv.background-color = rgb(randR, randG, randB);
Uncaught ReferenceError: pattern is not defined at onload
<body id="theBody" onload="pattern()">
I' really appreciate some help here. I don't see what I did wrong.
Thanks
newDiv.backgroundColor = rgb(randR, randG, randB);
and add after the function definition
window.onload = pattern;
background-color is not a valid property name, and the value you assign to it should be a string (quoted, with variables interpolated using string concatenation). In other words:
newDiv.style.backgroundColor = 'rgb(' + [randR, randG, randB] + ')';
A few other notes:
Use document.getElementById instead of getElementById;
You misspelled document in document.createElement("div");
You should use .style.width and .style.height to set the dimensions of your div (and make sure the values you assign end in a unit, like 'px').
Demo:
function pattern() {
var the_body = document.getElementById("theBody");
var xPos = 25;
var yPos = 25;
var width = 300;
var height = 300;
while (xPos <= 105) {
var newDiv = document.createElement("div");
newDiv.style.left = xPos + 'px';
newDiv.style.top = yPos + 'px';
newDiv.style.width = width + 'px';
newDiv.style.height = height + 'px';
var randR = Math.floor(Math.random() * 255);
var randG = Math.floor(Math.random() * 255);
var randB = Math.floor(Math.random() * 255);
newDiv.style.backgroundColor = 'rgb(' + [randR, randG, randB] + ')';
the_body.appendChild(newDiv);
xPos += 10;
yPos += 10;
width -= 20;
height -= 20;
}
}
<!doctype html>
<html>
<head>
<style>
div {
position: absolute;
}
</style>
</head>
<body id="theBody" onload="pattern()">
</body>
</html>

Categories