Can't create several divs inside another div - javascript

I'm trying to create several divs inside the div which has the id "second".
<div>
<div class="content" id="first" hidden></div>
<div class="content" id="second" hidden></div>
<div class="content" id="third" hidden></div>
</div>
I've tried the following function but it does not work.
function createboard(){
for(let i=0;i<10;i++){
let newDiv = document.createElement("div");
newDiv.className="column";
newDiv.id="column";
document.getElementById("second").appendChild(newDiv);
}
}
The function that removes the hidden attribute from the div
function hide_div(){
if(document.getElementById("cavidades").value == "" || document.getElementById("sementes").value==""){
alert("Preencha todos os dados de jogo antes de começar");
}
else{
var start_div = document.getElementById("start_div");
start_div.hidden=true;
var login=document.getElementById("login");
login.hidden=true;
var first = document.getElementById("first");
var second = document.getElementById("second");
var third = document.getElementById("third");
var inside=document.getElementById("inside");
first.hidden=false;
second.hidden=false;
third.hidden=false;
inside.hidden=false;
}
Both are supposed to run when this button is clicked
<button hidden type="submit" id="start" onclick="hide_div() ; createboard()">Começar</button>
CSS of both divs
div#second{
float: left;
background-color: lightgray;
height: 500px;
width: 500px;
border: 5px solid black;
}
div#column{
float: left;
background-color: green;
height: 50px;
width: 50px;
border: 5px solid yellow;
}

It doesn't work because your divs are hidden, try this:
function createboard(){
for(let i=0;i<10;i++){
let newDiv = document.createElement("div");
newDiv.className="column";
document.getElementById("second").appendChild(newDiv);
//just add this line
document.getElementById("second").hidden = false // to show the div
}
}

Related

Javascript createelement button not clickable

Hello I'm building a todo app with javascript. and i started to make divs and buttons from creating with document.createElement but when i create buttons to remove lists only one button which is written in html is clickable and remove div ,other buttons that created with javascript not clickable,please can anyone tell me how to fix
let menu = document.querySelector(".bs");
let btn1 = document.querySelector(".btn");
let btn2 = document.querySelector(".btn3");
let inp = document.querySelector(".input");
let bsd = document.querySelector(".sss");
let brs = document.querySelector(".marker");
btn1.addEventListener("click", function(){
let br = document.createElement("DIV");
br.className = "red";
br.innerHTML = inp.value;
menu.appendChild(br);
let ttt = document.createElement("BUTTON");
ttt.className = "marker";
ttt.innerHTML = "Remove";
br.appendChild(ttt);
});
brs.addEventListener("click", function(){
let bred = document.querySelector(".but");
let drp = document.querySelector(".red");
bred.removeChild(drp);
});
.red {
background-color: dodgerblue;
width: 100%;
min-height: 50px;
display: flex;
align-items: center;
justify-content: space-around;
color: white;
margin: 30px 0;
}
.marker {
background-color:white;
border:none;
padding:10px 20px;
}
<body>
<div class="but">
<div class="red">
<button class="marker">Remove</button>
</div>
<div class="bs"></div>
</div>
<input type="text" class="input">
<button class="btn">Add</button>
<button class="btn3">Remove</button>
</body>
that
You need to add the click listener to "remove" buttons when you create them.
The following does this:
let menu = document.querySelector(".bs");
let btn1 = document.querySelector(".btn");
let btn2 = document.querySelector(".btn3");
let inp = document.querySelector(".input");
let bsd = document.querySelector(".sss");
let brs = document.querySelector(".marker");
let addBr = () => {
let br = document.createElement("DIV");
br.className = "red";
br.innerHTML = inp.value;
menu.appendChild(br);
let ttt = document.createElement("BUTTON");
ttt.className = "marker";
ttt.innerHTML = "Remove";
br.appendChild(ttt);
// This is the important change. Part of creating the .ttt element
// is setting up its event listeners!
ttt.addEventListener('click', () => br.remove());
};
btn1.addEventListener("click", addBr);
// Call `addBr` once to add the initial element
addBr();
.red {
background-color: dodgerblue;
width: 100%;
min-height: 50px;
display: flex;
align-items: center;
justify-content: space-around;
color: white;
margin: 30px 0;
}
.marker {
background-color:white;
border:none;
padding:10px 20px;
}
<body>
<div class="but">
<div class="bs"></div>
</div>
<input type="text" class="input">
<button class="btn">Add</button>
<button class="btn3">Remove</button>
</body>

click a button to delete itself and its parent div

--- UPDATED QUESTION ---
Thanks for all the answers. I wrote the JS code to delete the parent div when clicking its corresponding button in my JS PRACTICE!!!
However, the same JS code does not work in my real JS project where all the parent div are created dynamically. The complete code can be found below.
There is no error but the JS code just does not work. Any ideas?
BELOW IS THE SIMPLIFIED **REAL JS PROJECT ** COMPLETE CODE
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload Imgs</title>
<style type="text/css">
.container {
width: 100%;
}
.display-area {
width: 100%;
height: auto;
display: flex;
justify-content: flex-start;
flex-wrap: wrap;
}
img {
max-width: 100%;
}
.image-preview {
width: 80%;
min-height: 300px;
border: 2px dashed #dddddd;
display: block;
/*default text*/
display: flex;
align-items: center;
justify-content: center;
font-weight: bold;
color: #cccccc;
}
.newbtns {
border: 0;
background: lightgrey;
text-shadow: 1px 1px 1px white;
border: 1px solid #999;
position: absolute;
display: block;
}
</style>
</head>
<body>
<div class="container">
<div id='inputFiles'><input type="file" class="file" name="image_uploads" accept="image/png, image/jpeg, image/jpg"
multiple></div>
<div class="display-area" id='imgDisplay'>
</div>
<div id="defaultContent">
<p>No images</p>
</div>
<button type="button" value="Reload page" onclick="window.location.reload()">Reload Page</button>
</div>
</div>
</body>
<script>
var input = document.querySelector('input');
var uploadBox = document.getElementById('uploadBox');
var defaultContent = document.getElementById('defaultContent');
var imgDisplay = document.getElementById('imgDisplay')
//upload & preview
input.addEventListener('change', function () {
var imgFiles = input.files;
defaultContent.style.display = 'none';
for (var i = 0; i < imgFiles.length; i++) {
var imgDiv = document.createElement('div');
imgDiv.className = 'imgBox';
imgDiv.id = 'box' + i;
imgDiv.style.width = "20%";
var images = document.createElement('img');
images.src = URL.createObjectURL(imgFiles[i]);
var newbtn = document.createElement("button");
newbtn.type = "button";
newbtn.className = "newbtns";
newbtn.innerHTML = "X";
newbtn.style.color = "orange";
newbtn.style.background = 'red';
newbtn.id = 'newbtn' + i;
imgDiv.appendChild(newbtn);
imgDiv.appendChild(images);
imgDisplay.appendChild(imgDiv);
}
});
allButtons = document.getElementsByTagName('button');
for (var n = 0; n < allButtons.length; n++) {
if (allButtons[n].getAttribute('id') === 'newbtn' + n) {
allButtons[n].onclick = function () {
this.parentNode.parentNode.removeChild(this.parentNode);
}
} else { };
}
</script>
</html>
you can do something like this:
const buttonOne = document.getElementById('btn1');
const buttonTwo = document.getElementById('btn2');
buttonOne.addEventListener("click", () => deleteElementAndThisChildNodes('box1'))
buttonTwo.addEventListener("click", () => deleteElementAndThisChildNodes('box2'))
function deleteElementAndThisChildNodes(parentId) {
document.getElementById(parentId).remove()
}
To each of your button elements add onclick="DeleteParent(this)" then outside of your dynamic divs include the following:
<script type="text/javascript">
function DeleteParent(button){
button.parentElement.remove();
}
</script>
You can do this:
const display = document.getElementById("imgdisplayarea");
display.addEventListener("click", e => {
if(e.target.tagName === 'BUTTON'){
//if an element within a display div for a button, remove your father
e.target.parentNode.remove();
}
});
Here is a very simple example that works exactly how you want it (based on your question):
function disable() {
document.getElementById("demo").style.display = "none";
}
<div id="demo">
<button onclick="disable()">
Click Me
</button>
<h3>
This is part of the div
</h3>
</div>

How do I make each new input appear in a new box

I want to know how to make it so that when the button is clicked and a new input is added, it does not take the place of the old one, but appears in a new bix leaving the old one.
<!DOCTYPE html>
<html>
<body>
<div id="itemcreator" class="itm">
<form id="form1">
<!--where the user inputs the item-->
Item: <input name="item" type="text" size="20">
</form>
<button onclick="outputname()">Add</button>
</div>
<div class="box" id="duplicater">
<p id="output"></p>
</div>
<script type="text/javascript">
var i = 0;
var original = document.getElementById('duplicater');
duplication function
function duplicate() {
i = i + 1;
var clone = original.cloneNode(true);
clone.id = "duplicetor" + ++i;
original.parentNode.appendChild(clone);
}
function to output the item.
function outputname() {
var x=document.getElementById("form1") ;
item = x.elements.namedItem("item").value;
if (item !== ""){
document.getElementById("output").innerHTML=item;
duplicater.style.display = "block";
document.getElementById("addTrade").style.left = "7px";
itemMkrWindow.style.display = "none";
}
}
</script>
.box {
display: none;
border-radius: 5px;
border-width: 1px;
border-color: black;
border-style: solid;
}
Cant Get What you are trying to do, but maybe this will help:
var i = 0;
var original = document.getElementById('duplicater');
function duplicate() {
i = i + 1;
var clone = original.cloneNode(true);
clone.id = "duplicetor" + ++i;
original.parentNode.appendChild(clone);
}
function outputname() {
var x=document.getElementById("form1") ;
item = x.elements.namedItem("item").value;
if (item !== ""){
var createdItem = document.createElement('P');
createdItem.setAttribute('id', 'output');
var text = document.createTextNode(item);
createdItem.appendChild(text);
var container = document.getElementById("duplicater");
container.appendChild(createdItem);
}
}
this would be CSS:
.box {
border-radius: 5px;
border-width: 1px;
border-color: black;
border-style: solid;
}
#output{
display: block;
background-color: red;
width: 100px;
height: 50px;
}
check this link also

Make a left border move to center in javascript

I am making a change in my current div such that I need a vertical line at the middle of my div. So, I saw many solutions in which they are making a left border and with the help of left property they are moving it 50% of the left (which is actually is in middle).
Here is how I am making my div:
if (id == "Metricbar" ) {
var Parentdiv = document.getElementById("homeContainer");
var rowDiv = document.createElement("article");
rowDiv.setAttribute("class", "col-sm-12 col-md-12 col-lg-12");
rowDiv.style.border = "1px solid #ddd";
rowDiv.style.marginBottom = "1px";
rowDiv.style.marginTop = "1px";
rowDiv.style.borderLeft = "2px solid #ddd";
Parentdiv.appendChild(rowDiv);
var ctrlDiv = document.createElement("div");
ctrlDiv.setAttribute("data-widget-editbutton", "false");
ctrlDiv.className = "jarviswidget";
ctrlDiv.setAttribute("data-widget-fullscreenbutton", "false");
ctrlDiv.id = id;
var temp = $compile(ctrlDiv)($scope);
angular.element(rowDiv).append(temp);
rowDiv.appendChild(ctrlDiv);
}
My question is how will I move it to the center. Is there any way to do that?
I have tried:
rowDiv.style.borderLeft.marginLeft = "50%";
rowDiv.style.borderLeft.Left = "50%";
rowDiv.style.borderLeft.leftMargin = "50%";
But none of this is helping. Can anybody point me in the right direction.
HTML File :
<section id="widget-grid" class="" style="padding-left:13px;padding-right:13px;">
<div class="row" id="homeContainer"></div>
<div class="modaldialogs" style="display: none">
<div class="center">
<img alt="" src="img/ajax-loader.gif" />
</div>
</div>
</section>
But I am using this div multiple times. I am here checking on the basis of id.
I want this black line as shown in image
If you only need to add a vertical line to the article element let's go with the simplest solution - CSS!
First, give the article element and position: relative or position: absolute. Then add a :after psuedo-element to create a vertical bar.
The HTML and Javascript have are untouched (except a small change to the borders on the article) so you only need to add a few lines of CSS.
var Parentdiv = document.getElementById("homeContainer");
var rowDiv = document.createElement("article");
rowDiv.setAttribute("class", "col-sm-12 col-md-12 col-lg-12");
rowDiv.style.marginBottom = "1px";
rowDiv.style.marginTop = "1px";
rowDiv.style.borderTop = "2px solid #ddd";
rowDiv.style.borderRight = "2px solid #ddd";
rowDiv.style.borderBottom = "2px solid #ddd";
rowDiv.style.borderLeft = "2px solid #ddd";
Parentdiv.appendChild(rowDiv);
#homeContainer article {
height: 300px; // Just for demo purposes since we have no content
position: relative;
}
#homeContainer article:after {
content: "";
height: 100%;
width: 0px;
position: absolute;
border-right: 3px solid #000000;
right: 50%;
}
<section id="widget-grid" class="" style="padding-left:13px;padding-right:13px;">
<div class="row" id="homeContainer"></div>
<div class="modaldialogs" style="display: none">
<div class="center">
<img alt="" src="img/ajax-loader.gif" />
</div>
</div>
</section>
I found answer. We can have a new div by using javascript and a new class name which will have a border-left.
This is my solution
var element = document.createElement('div');
element.className = "divider";
rowDiv.appendChild(element); \\appending it to parent
CSS
.divider {
content: "";
position: absolute;
z-index:1;
top: 0;
bottom: 0;
left: 45%;
border-left: 2px solid #C0C0C0;
}

Displaying divs when the ones before are full with JQuery

I would like to display divs when the div contents before is full of words and continue to fill this new div with the rest of the words.
I don't know how to do it. In fact, in the code below I wrote that the div is displayed on click of a button. I also can't set the "fill-action" explained above.
The limit of the words in one div has to be settable from the code.
For example, if I set the limit to two words and there are only two words to be displayed, the second div shouldn't be created.
But If there are four words to be displayed and the limit is still on two words,
the second div has to be created and has to be filled with the third and fourth words.
Another problem is that if I write HTML text (e.g. <font color="#ff0000">), the tags (e.g. <font) shouldn't be considered as a word.
Jsfiddle
HTML:
<div id="faketxt" contenteditable>Write Here</div>
<button id='btn'>OK</button>
<div id='casella' class='fakes'></div>
CSS:
#faketxt {
-moz-appearance: textfield-multiline;
-webkit-appearance: textarea;
border: 1px solid gray;
height: 28px;
overflow: auto;
padding: 2px;
resize: both;
width: 400px;
}
#casella{
width: 150px;
height: 300px;
font-size: 10px;
border-style: solid;
}
.fakes{
width: 150px;
height: 300px;
font-size: 10px;
border-style: solid;
}
JQUERY:
$('#btn').click(function() {
var primo = document.getElementById('faketxt');
var secondo = document.getElementById('casella');
secondo.innerHTML = primo.innerHTML;
var myDiv = $('#casella');
myDiv.text(myDiv.text().substring(0,5)) //This is when the div is "full"
});
document.getElementById("btn").onclick = function () {
var ok = true;
if (ok === true) {
var div = document.createElement('div');
div.className = 'fakes';
document.getElementsByTagName('body')[0].appendChild(div);
}
};
In this case I set that the div is full when there are 5 letters, so the word "Here" has to be displayed in the second div...
Is this possible?
I can't figure it out.
for displaying divs at right position
css:
.fakes{
width: 150px;
height: 300px;
font-size: 10px;
border-style: solid;
display : inline-block;
}
#boxes{
display : flex;
}
HTML
<div id="faketxt" contenteditable>Write Here</div>
<button id='btn'>OK</button><br>
<div id="boxes">
<div id='casella' class='fakes'></div>
</div>
Use String.split() to separate the words (by spaces) and add a div container for each word using Array.foreach(). Also with this approach, use Array.shift() to set the text of the myDiv element (i.e. with id="casella") to the first word.
UPDATE:
Per the changing requirements, the code below now has a number input for the word limit. It then strips HTML codes (using the HTML entities) using a regular expression and then uses a counter to add words to newly created div elements. The functionality to create a new div element has been abstracted to the function createdDiv().
$('#btn').click(function() {
var primo = document.getElementById('faketxt');
var wordLimit = $('#wordLimit').val();
//strip html characters from string and use a regular expression
//to split based on white-space characters
var words = primo.innerHTML.replace(/(<([^>]+)>)/ig,"").split(/\s/);
if (words.length) {
var count = 0;
var div = createDiv();
words.forEach(function(word) {
if (++count > wordLimit) {
count = 0; //reset counter
div = createDiv();
}
if (div.innerHTML) {
div.append(' ');
}
div.append(word);
});
}
});
function createDiv() {
div = document.createElement('div'); //could use jQuery $('div') instead
div.className = 'fakes';
document.body.append(div);
return div;
}
#faketxt {
-moz-appearance: textfield-multiline;
-webkit-appearance: textarea;
border: 1px solid gray;
height: 28px;
overflow: auto;
padding: 2px;
resize: both;
width: 400px;
}
#casella {
width: 150px;
height: 300px;
font-size: 10px;
border-style: solid;
}
.fakes {
width: 150px;
height: 300px;
font-size: 10px;
border-style: solid;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Word Limit:
<input type="number" id="wordLimit" value="1" />
</div>
<div id="faketxt" contenteditable>Write Here</div>
<button id='btn'>OK</button>
var myDiv = $('#casella');
var primo = document.getElementById('faketxt');
var secondo = document.getElementById('casella');
$('#btn').click(function() {
var inputArray = primo.innerHTML.split(" ");
var secDivContent = '';
if(inputArray[0].length > 5 || primo.innerHTML.length > 5 ) {
secDivContent = primo.innerHTML.substr(5);
}
var div = document.createElement('div');
div.className = 'fakes';
div.innerHTML = secDivContent;
document.getElementsByTagName('body')[0].appendChild(div);
});

Categories