How to append a div to the body? - javascript

I am supposed to assign .moon and .planet to the "planet" class and add a background colour to it, so I need to create a div. I have no idea on how to append a div to the body.
The code below shows what I'm currently trying. Please point out my mistake(s).
<html>
<head>
<meta charset="utf-8">
<title>Challenge: Create a solar system</title>
<style>
body {
background-color: black;
padding: 10px;
}
.planet {
width: 100px;
height: 100px;
border-radius: 50%;
text-align: center;
padding: 10px;
position: relative;
}
.moon {
position: absolute;
width: 30px;
height: 30px;
border-radius: 50%;
background: rgb(237, 237, 237);
}
</style>
</head>
<body>
<script>
var bodyEl = document.querySelector("body");
for (var i = 0; i < planetsNode.length; i++) {
var planetsNode = document.createElement("div");
planetsNode[i].className += "planet";
planetsNode.body.backgroundColor = "rgb(235, 12, 235)";
document.body.appendChild(planetsNode);
}
</script>
</body>
</html>

You are accessing the variable 'planetsNode' before it gets created and you are accessing body from 'planetNode' element while assigning background color.
Hope this might help.
<script>
var body = document.querySelector("body");
var planetsNode = document.createElement("div");
planetsNode.className = "planet";
body.style.backgroundColor = "rgb(235, 12, 235)";
body.appendChild(planetsNode);
</script>
I don't know why you are using loop.

You are trying to access 'length' property of the 'planetsNode' variable before it has been created. If you are looking to create a new div for each planet create an array of planets and loop through them.
<script>
var planets = [
["Mercury", "46.3, 46.3, 46.3"],
["Venus", "80.4, 78.4, 76.1"],
["Earth", "34.9, 37.3, 51.4"],
["Mars", "99.6, 52.9, 37.3"],
["Jupiter", "85.1, 74.9, 65.1"],
["Saturn", "86.3, 73.7, 50.6"],
["Uranus", "76.5, 91.4, 92.5"],
["Neptune", "28.2, 47.5, 98.8"]
];
for (var i = 0; i < planets.length; i++) {
var planetNode = document.createElement("div");
planetNode.style.backgroundColor = "rgb(" + planets[i][1] + ")";
var nameNode = document.createTextNode(planets[i][0]);
planetNode.appendChild(nameNode);
var body = document.querySelector("body");
body.appendChild(planetNode);
}
</script>

Related

How to set the window's Y middle to element's Y middle?

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>

Random Box Generator

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>

Create dynamic Rectangle collection in html using js

Hello All I am a beginner in html and js, and I am trying to create a webpage containing a rectangle collection in which when a new rectangle is created is placed beside the previous rectangle.
I have created a div element and trying to add newly created div (rectangle shape with background color different based on condition), but I am not able to get the desired result.
<html>
<head>
<title>parkIn</title>
<meta charset="utf-8" />
</head>
<style>
.ParkSlots {
border: solid 1px;
width: 60%;
height: 400px;
top: 50%;
left: 50%;
position: fixed;
transform: translate(-50%, -50%);
display: inline;
}
.row:before,
.row:after {
content: "";
display: table;
clear: both;
}
.col-1 {
width: 15%;
margin-left: 10px;
height: 350px;
padding: 2px;
}
</style>
<body onload="viewCreate()">
<div class="ParkSlots">
<div class="row" id="content">
</div>
</div>
</body>
<script language="javascript">
function viewCreate() {
for (int i = 0; i < 5; i++) {
if (i % 2 == 0) {
createGreenBox();
} else {
createRedBox();
}
}
}
function createRedBox() {
var = document.createElement('div');
div.className = 'col-1';
div.style.backgroundColor = 'red';
document.getElementById('content').appendChild(div);
}
function createGreenBox() {
var = document.createElement('div');
div.className = 'col-1';
div.style.backgroundColor = 'lightgreen';
document.getElementById('content').appendChild(div);
}
</script>
</html>
I want an output that looks something like this:
Just in glancing at your code, I see at least two typos:
for (int i = 0; i < 5; i++) { - in JS, int is not used in this way. Use var i = 0...
var = document.createElement('div'); - you're missing a variable name on this line in both create box functions. I assume, from the rest of the code you need var div = document.createElement('div');
The rest will be CSS. In your stylesheet you're applying the border to the outter most containing div, from you're example, you need to apply that to the .col-1 class. You'll also want to use display:inline-block on that class, and set widths and margins to play nicely with the border size. I took the liberty of creating a jsfiddle for you with my recommended changes.

In javascript when creating a new object, the array property in it does not initializes as a new one

I am creating 5 new objects of type "RoundDiv" using for loop, it has a property "weirdArray", which is an empty array. Upon calling "init()" method. "someValue" is pushed into the "weirdArray".
The problem is "someValue" is pushed only once each time a new object of type "RounDiv" is created but on clicking any "roundDiv" the console log shows 5 elements in the array, whereas there should be only one.
"use strict";
var roundDivPrototype = {
weirdArray: new Array(),
init: function(label) {
this.weirdArray.push("someValue");
var me = this;
var body = document.body;
var div = document.createElement("div");
div.className = "roundDiv";
div.innerText = label;
div.addEventListener("click", function(e) {
alert("Length of array: " + me.weirdArray.length);
console.log(me.weirdArray); //me=this
});
body.appendChild(div);
}
};
var RoundDiv = function(label) {
this.init(label);
};
RoundDiv.prototype = roundDivPrototype;
for (var i = 0; i < 5; i++) {
new RoundDiv(i);
}
body {
background-color: teal;
text-align: center;
width: 100%;
}
.roundDiv {
display: inline-block;
height: 100px;
width: 100px;
background-color: whitesmoke;
margin: 10px;
border: solid;
border-radius: 50%;
text-align: center;
font-size: 5em;
box-sizing: border-box;
cursor: pointer;
line-height: 100px;
}
<body>
<script src="js/main.js"></script>
</body>
I figured out a possible solution to the problem:
"use strict";
var roundDivPrototype = {
weirdArray: undefined,
init: function(label) {
this.weirdArray = new Array(); //Change in code above
this.weirdArray.push("someValue"); //Change in code above
var me = this;
var body = document.body;
var div = document.createElement("div");
div.className = "roundDiv";
div.innerText = label;
div.addEventListener("click", function(e) {
alert("Length of array: " + me.weirdArray.length); //me=this
console.log(me.weirdArray); //me=this
});
body.appendChild(div);
}
};
var RoundDiv = function(label) {
this.init(label);
};
RoundDiv.prototype = roundDivPrototype;
for (var i = 0; i < 5; i++) {
new RoundDiv(i);
}
body {
background-color: teal;
text-align: center;
width: 100%;
}
.roundDiv {
display: inline-block;
height: 100px;
width: 100px;
background-color: whitesmoke;
margin: 10px;
border: solid;
border-radius: 50%;
text-align: center;
font-size: 5em;
box-sizing: border-box;
cursor: pointer;
line-height: 100px;
}
<body>
<script src="js/main.js"></script>
</body>
Although I figured out a possible solution to the problem but still want to know why previous values in "weirdArray" are present when I'm creating a new object of type "RoundDiv"...
Your contribution is deeply appreciated :)
In your first example, you instantiate weirdArray in the object prototype, making this array property static. Therefore, each of your RoundDiv objects will share the same array to store your data.
Instantiating it in the init function as you do in your second example solves the problem. A new instance of weirdArray will be created each time you create a new RoundDiv.
See this fiddle that shows for each example how many times a new array is created, when, and the array size after each push.

Creating <div> grid with JQuery for loop

I'm new to web development but have a pretty solid programming background. I've tried multiple ways to create a element programatically based on user input. I'm trying to essentially create a grid through JQuery.
I'm tackling this problem by storing the user input into a variable and going through a for loop to create the grid. Here is the code for the .js file:
var rows = 8;
var columns = 8;
var $row = $("<div />", {class: 'row'});
var $square = $("<div />", {class: 'square'});
$(document).ready(function(){
for(var i = 0; i < rows; i++){
$("#wrapper").append($row);
}
for(var i = 0; i < columns; i++){
$(".row").append($square);
}
});
Now for some reason, this code only creates one row in #wrapper and one square in the row. I've tried copying the example CSS files that tackle this problem but nothing seems to work. Here's what I have right now for my CSS:
#wrapper {
width: 850px;
height: 850px;
margin-top: 100px;
margin-left: auto;
margin-right: auto;
background: #000000;
}
.row {
width: auto;
height: 100px;
background: #313131;
}
.square {
width: 100px;
height: 100px;
margin: 0px;
outline: 1px solid;
display: inline-block;
float: left;
background: #FFFFFF;
}
And here's my HTML:
<!doctype html>
<html>
<head>
<title>Draw Grid</title>
<link rel="stylesheet" type="text/css" href="theme.css" >
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="draw.js"></script>
</head>
<body>
<div id="wrapper">
</div>
</body>
</html>
Can anybody help me out? I'm so confused. I've tried everything. Is this a CSS formatting error?
The problem is you are creating only one row and square objects, you need to use cloned copies else they are just copy
var rows = 8;
var columns = 8;
var $row = $("<div />", {
class: 'row'
});
var $square = $("<div />", {
class: 'square'
});
$(document).ready(function () {
//add columns to the the temp row object
for (var i = 0; i < columns; i++) {
$row.append($square.clone());
}
//clone the temp row object with the columns to the wrapper
for (var i = 0; i < rows; i++) {
$("#wrapper").append($row.clone());
}
});
Demo: Fiddle

Categories

Resources