Invalid assignment and onload problems in javascript/html - javascript

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>

Related

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 move multiple elements on mousemove

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.

Adding HTML rectangles with for loop in javascript

I would like to draw a 2 x 2 grid of blue rectangles on an HTML page, but my code does not draw anything. I create a fragment toAdd that I want to add later, and add divs to toAdd. I'm not quite sure where I went wrong, and when I tried to add a console.log() I could confirm that addSquares is being called. Do I need to add anything to the HTML file, or is there a mistake in this code?
I also noticed that this code produces five divs: b0, b1, b2, b3, b1 (returns error) and I'm not sure what is wrong with my for loop.
dim = 2;
width = 50;
height = 50;
// add the squares
function addSquares()
{
var toAdd = document.createDocumentFragment();
for(var i = 0; i < dim; i++)
{
for(var j = 0; j < dim; j++)
{
var label = j + i * dim;
var name = "b" + label;
console.log(name)
var div = document.createElement(name);
div.style.width = width + "px";
div.style.height = height + "px";
div.style.left = width * j + "px";
div.style.top = height * i + "px";
div.style.position = "absolute";
div.style.color = "blue";
toAdd.appendChild(div);
}
}
document.appendChild(toAdd);
}
So it appears that there's two issues. The first being that you need to change:
document.appendChild(toAdd);
to
document.body.appendChild(toAdd);
Your second issue is that your using the wrong CSS styling declaration. Your divs are in the DOM but don't have a backgroundColor assigned to them, which in turn gives the illusion that they're not there. So instead of color use backgroundColor.
dim = 2;
width = 50;
height = 50;
// add the squares
function addSquares()
{
var toAdd = document.createDocumentFragment();
for(var i = 0; i < dim; i++)
{
for(var j = 0; j < dim; j++)
{
var label = j + i * dim;
var name = "b" + label;
console.log(name)
var div = document.createElement(name);
div.style.width = width + "px";
div.style.height = height + "px";
div.style.left = width * j + "px";
div.style.top = height * i + "px";
div.style.position = "absolute";
div.style.backgroundColor = "blue";
toAdd.appendChild(div);
}
}
document.body.appendChild(toAdd);
}
addSquares();
I just wanted to point out a little trick to you...
You have this:
div.style.width = width + "px";
div.style.height = height + "px";
div.style.left = width * j + "px";
div.style.top = height * i + "px";
div.style.position = "absolute";
div.style.backgroundColor = "blue";
I believe can be written like this ES6:
div.style.cssText = `width: ${width + "px"};
height: ${height + "px"};
left: ${width * j + "px"};
top: ${height * i + "px"};
position: absolute;
backgroundColor: blue;`
As far as I know .cssText = will replace the existing inline...
To append the existing inline use .cssText +=
I'm sure this will help you in the long run.

remove elements in dom animation

I try to delete some animated elements if they pass the screen height. For that an array will be checked in a for loop. The array have the id's of the created div's. Theoretically should all div's which have an y position which is higher than the screen height become removed and the values from the array deleted. But now it becomes every n element removed. Know anyone the issue for that? box = setInterval(newbox, 1000); affect the behaviour when I change the interval time.
fiddle
var cx = wwidth / 100;
var cy = wheight / 100;
var maxpos = cx * 80;
var speed;
var box;
var counter = 0;
var rectids = [];
var deleting;
function newbox() {
var allpositions = Array(0, cx * 25, cx * 50, cx * 75);
var rectpos = allpositions[Math.floor(Math.random() * allpositions.length)];
speed = 0;
var box = document.createElement('div');
counter++;
box.className = "game-btn";
box.id = 'n' + counter;
box.style.cssText = "top:" + speed + "px;left:" + rectpos + "px;width:" + cx * 25 + "px;height:" + cy * 10 + "px;position:absolute";
console.log(rectpos);
document.body.appendChild(box);
rectids.push(box.id);
}
function game() {
box = setInterval(newbox, 1000);
animaterects = setInterval(function () {
speed += cx / 300;
$(".game-btn").css("top", "+=" + speed + "px");
}, 10);
deleting = setInterval(function () {
for (var i = 0; i < rectids.length; i++) {
var x = $("#" + rectids[i]).position();
if (x.top > wheight) {
$("#" + rectids[i]).remove();
rectids.splice(rectids[i]);
}
}
}, 50);
}
game();

How do I add a new image to this code , so I have 2 alternating images?

<HTML><head>
<Script language="JavaScript">
<!--
function changePos()
{
width = document.body.clientWidth; //the width of the current document
height = document.body.clientHeight; //the height of the current document
Hoffset = img.offsetHeight;
Woffset = img.offsetWidth;
img.style.left = xPos;
img.style.top = yPos;
if (yon)
{
yPos = yPos + 5;
}
else
{
yPos = yPos - 5;
}
if(yPos < -Hoffset)
{
yon = 1; yPos = -Hoffset;
}
if(yPos >= height)
{
yon = 0; yPos = height;
}
}
//-->
</Script>
</head>
<body>
<IMG id="img" style="POSITION: absolute" src="Images\Colored.jpg">
<SCRIPT language=JavaScript>
<!--
var height = 0;
var Hoffset = 0;
var Woffset = 0;
var yon = 0; //false
var xPos = 20;
var yPos = document.body.clientHeight;
var Timer1 = setInterval('changePos()',30);
//-->
</Script>
</BODY>
</HTML>
So my question is , how do I add a new image to this animation , and make it in a way that i alternates with the old one (Example : the image I have is colored , and I want to add a black&white image to it , so they alternate together !!!
to start off very simply, you could simply create an array of images:
var images = new Array( "image1.jpg",
"image2.jpg",
"image3.jpg");
Then you declare an img element in your html like :
<img id="img1" src="image3.jpg" />
And then just add this to your function:
document.getElementById("img1").src = images[0] // or whatever image number you want.
Have a look here:
http://www.daniweb.com/web-development/javascript-dhtml-ajax/threads/131227/changing-images-in-html
Perhaps this:
<html><head>
<script language="JavaScript"><!--
var timer1,Hoffset = 0,Woffset = 0,
xPos = 20,ypos,
width = document.body.clientWidth,
height=yPos=document.body.clientHeight,yon = 0; //false
window.onload=function() {
Timer1 = setInterval(changePos,30);
}
function changePos() {
var img = document.getElementById('img');
Hoffset = img.offsetHeight;
Woffset = img.offsetWidth;
yPos += (yon)?5:-5;
if(yPos < -Hoffset) {
yon = 1; yPos = -Hoffset;
}
if(yPos >= height) {
yon = 0; yPos = height;
}
img.src = img.src.indexOf("Colored.jpg"!=-1)?"Images\BW.jpg":"Images\Colored.jpg";
img.style.left = xPos + "px";
img.style.top = yPos + "px";
}
//-->
</script>
</head>
<body>
<img id="img" style="position: absolute" src="Images\Colored.jpg">
</body>
</html>

Categories