Creating and styling elements dynamically - javascript

I want to dynamically create 6 boxes when the page is loaded. They should be inline-block, so eventually it will look like 3 lines, with 2 boxes on each line.
I tried the code below without any JavaScript (just used some static HTML and CSS), and it seemed to work fine.
Generally, the script looks fine to me -- however, it does nothing. What am I doing wrong? Is it something about the order of the CSS and the JavaScript?
style1.css:
* {
margin:0;
padding:0;
}
header,section,nav,aside,footer{
display:block;
}
.wrapper{
position: relative;
height: 2150px;
width: 900px;
background-color: #336b98;
margin: 0 auto;
}
section#contentSection_layout3{
position: absolute;
top:193px;
height: 1957px;
width: 900px;
border-right: solid 1px #FFF;
}
HTML & JavaScript:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="includes/style1.css">
<script src="includes/JavaScript.js"></script>
<title> EX </title>
<script>
window.onload = function(){
var boxesNum = 6;
for(var i = 0; i < boxesNum; i++){
var rect = new rect();
rect.setAttribute('display', 'inline-block');
rect.setAttribute('margin-left', '200');
rect.setAttribute('margin-top', '100');
rect.setAttribute('height', '150');
rect.setAttribute('width', '150');
rect.setAttribute('background-color', '#FFF');
document.getElementById('contentSection_layout3').appendChild(rect);
}
};
</script>
</head>
<body>
<div class="wrapper">
<section id="contentSection_layout3"></section>
</div>
</body>
</html>

var rect = new rect();
Unless you have defined rect elsewhere, you want:
var rect = document.createElement('div');
Also, setAttribute is not for styles, style is for styles.
rect.style.display = 'inline-block';
rect.style.marginLeft '200px';
rect.style.marginTop = '100px';
rect.style.height = '150px';
rect.style.width = '150px';
rect.style.backgroundColor = '#FFF';
Also, don't forget your pxs.

Related

Through javascript, how do I add a div to my html script with another div inside of it?

I am trying to create a notes app where the user can press a button, type text, which will spawn a box consisting of the text, which can be stretched and dragged around the screen. The part I am having trouble on is when the button is pressed and the text is inserted, the first div will spawn, but the child div isn't being spawned properly and acts strange.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="Filler/Style.css">
</head>
<body>
<button type="button" id="button">Add Filler</button>
<script src="Sketch.js"></script>
<script src="Filler/Sketch.js"></script>
<script src="Sidebar/Sketch.js"></script>
</body>
</html>
CSS
#mydiv {
position: absolute;
background-color: pink;
border: 1px solid black;
width: 200px;
height: 200px;
z-index: 4;
/* div able to be resised and scroll bar will be added if contents is too long .hidden*/
resize: both;
overflow: scroll;
/* create rounded borders */
border-radius: 15px;
-moz-border-radius: 15px;
text-align: center;
}
#mydivheader {
cursor: move;
z-index: 10;
}
Javascript
var myButton = document.getElementById("button");
myButton.addEventListener("click", clicked);
function clicked(){
const content = prompt("Div Contents");
const div = document.createElement('div');
const div2 = document.createElement('div');
div.id = "mydiv";
div.textContent = content;
div2.id = "mydivheader";
div2.style = "width: 100%; height: 15px;";
div2.textContent = content;
document.body.append(div);
div.appendChild(div2);
}
i didn't understood ur question properly.
is that the problem with content being generated twice. like one inside the parent div and another inside the child.
if so try this
function clicked(){
const content = prompt("Div Contents");
const div = document.createElement('div');
const div2 = document.createElement('div');
div.id = "mydiv";
div2.id = "mydivheader";
div2.style = "width: 100%; height: 15px;";
div2.textContent = content;
document.body.append(div);
div.appendChild(div2);
}

How to generate multiple div at random position inside a parent div using Javascript?

I am actually trying to create a game when someone hover on the gray area then it will ask if he wants to play if he confirm then random 5 div will appear in some different area of that parent div.
at first there should be only 1 big div. when someone will hover a mouse there will be option if he wants to play the game. then the big div will generate 5 small divs inside it. ( next i have delete if someone click small divs and need to track point, so its a small game for just my learning perpose
but i stuck here because i can't generate divs in random position. if you run my code you will see 3 divs verticaly appear when you confirm to play
function hoverinside(x) {
let answer = confirm("Do you want to play the game?");
if (answer == true) {
alert("Enjoy the game");
myFunction();
}
else {
alert("If you want to play just hover on the gray area again");
location.reload();
}
}
function myFunction() {
var element = document.createElement('div');
element.style.cssText = "width:55px; height:55px; background:green;";
document.body.appendChild(element);
var div1 = document.getElementById("square");
div1.insertBefore(element, div1.childNodes[5])
var element2 = document.createElement('div');
element2.style.cssText = "width:55px; height:55px; background:yellow;"
document.body.appendChild(element2);
var div2 = document.getElementById("square");
div2.insertBefore(element2, div2.childNodes[5])
var element3 = document.createElement('div');
element3.style.cssText = "width:55px; height:55px; background:red;";
document.body.appendChild(element3);
var div3 = document.getElementById("square");
div3.insertBefore(element3, div3.childNodes[5])
}
function removediv1() {
var element = document.getElementById("div2");
element.classList.remove("div2");
}
h1 {
font-style: bold;
color: brown;
}
#square{
height: 350px;
width: 700px;
background-color: rgb(170, 168, 168);
border: brown;
border-style: solid;
}
#square1{
height: 35px;
width: 70px;
background-color: rgb(245, 10, 10);
}
<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 href="style.css" rel="stylesheet" type="text/css">
<script src="gamejs.js"></script>
<title>Game</title>
</head>
<body onload=OpenInNewtab(google.com)>
<h1>Game:</h1>
<p>we will create the game over here. no problem just wait and chill and play with us.we will create the game over here. no problem just wait and chill and play with us.</p>
<h1>Points:</h1>
<br>
<div id="square" onmouseover="hoverinside(this)" >
<div id="child1"> </div>
</div>
</body>
</html>
this is my code
You can do something like this.
Steps
Create a child div
Add id to itnot necessay.
For distinguishing, add different colors
Make the child div as absolute
Add random left & right position styling to Child Div (This will assure the randomness)
Updated the code, so that child div be be confined inside parent div.
You can refer to this codepen: https://codepen.io/hackhimanshu1024/pen/JjrjOjK
Note: I am not adding hover and deleting events. You can handle it as per your code.
Note: Add other styles as per your requirements.
const parentBody = document.getElementById("root");
const btn1 = document.getElementById("btn1");
const btn2 = document.getElementById("btn2");
let i = 0, interval
function addDiv(cnt = 5) {
const div = document.createElement('div');
div.id = 'div';
div.style.top = `${Math.random() * 100}%`;
div.style.left = `${Math.random() * 100}%`;
div.style.backgroundColor = `rgb(${Math.random() * 100},${Math.random() * 100},${Math.random() * 100})`;
parentBody.appendChild(div);
i++;
if (i === cnt) clearInterval(interval);
}
function intervalDiv(){
i=0;
interval = setInterval(addDiv, 1000);
}
function multipleDiv(){
i=0;
while(i<5){
addDiv();
}
}
btn1.addEventListener('click', intervalDiv);
btn2.addEventListener('click', multipleDiv);
*{
box-sizing: border-box;
padding:0;
margin:0;
}
body{
height:100vh;
max-height:100vh;
max-width:100vw;
padding: 100px;
}
#root{
height:100%;
max-height:100%;
position: relative;
}
#btn1, #btn2{
position:relative;
z-index:200;
}
#div {
width: 200px;
height: 200px;
position: absolute;
transform: translate(-50%,-50%);
}
<html>
<body>
<div id="root">
<button id="btn1">CLICK ME on Interval</button>
<button id="btn2">CLICK ME for 5 times</button>
</div>
</body>
</html>

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>

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.

Put image on div randomly using javascript

I am making matching game that images in left and right are different, and users have to find(I put one more image in left side).
My problem is that I cannot call image on where I want. What should I have to fix? Thank you.
<!DOCTYPE html>
<html>
<head>
<style>
img {
position: absolute;
}
div {
position: absolute;
width: 500px;
height: 500px;
}
#leftside {
float: left;
}
#rightside {
float: right;
left: 500px;
border-left: 1px solid black
}
</style>
<script>
var numberOfFaces(5);
var theLeftSide = document.getElementById("leftSide");
function generateFaces() {
var createElement("img");
var position = Math.floor(Math.random() * 500);
img.src = 'http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png';
img.id = 'smileImage';
createElement.setAttribute("height", position);
createElement.setAttribute("width", position);
document.getElementById('leftSide').appendChild(img);
}
</script>
</head>
<body>
<h1>Matching Game</h1>
<p>Click on the extra smiling face on the left.</p>
<div id="leftside"></div>
<div id="rightside"></div>
</body>
</html>
You need to set something to the result of createElement('img'). For example, you can change that line to var img = createElement('img');
You never actually use theLeftSide.
createElement is actually document.createElement.
You never defined the variable createElement. Since we called it img earlier, do so now.
leftSide is not the ID of any element, but leftside is. Change it so that all usages are capitalized the same.
After that, you actually need to call generateFaces. Because the page is loaded top-to-bottom, JavaScript doesn't yet know about the div with the ID of leftSide. You have to wait until the page is finished loading to call the Javascript, and you can do that by adding window.onload = generateFaces to the end of your script.
Here's the final result:
<!DOCTYPE html>
<html>
<head>
<style>
img {
position: absolute;
}
div {
position: absolute;
width: 500px;
height: 500px;
}
#leftside {
float: left;
}
#rightside {
float: right;
left: 500px;
border-left: 1px solid black
}
</style>
<script>
function generateFaces() {
var img = document.createElement('img');
var position = Math.floor(Math.random() * 500);
img.src = 'http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png';
img.id = 'smileImage';
img.setAttribute('height', position);
img.setAttribute('width', position);
document.getElementById('leftSide').appendChild(img);
}
window.onload = generateFaces;
</script>
</head>
<body>
<h1>Matching Game</h1>
<p>Click on the extra smiling face on the left.</p>
<div id="leftSide"></div>
<div id="rightSide"></div>
</body>
</html>

Categories

Resources