Placing Existing Div into a DOM div? - javascript

I have a div that I have created with DOM/JS. I have another div that that I have some html in that i would like to place inside of the DOM div. I;m quite new to JS so any help would be appreciated.
//The DOM div
div = document.createElement("div");
div.style.position = "absolute";
div.style.left = "0px";
div.style.top = "0px";
div.style.width = "240px";
div.style.height = "auto";
div.style.background = "red";
div.style.padding = "15px 0px 0px 0px";
div.style.color = "white";
div.id = "chat";
<!--The existing div code-->
<div id="page-wrap">
<h2>Chat</h2>
<p id="name-area"></p>
<div id="chat-wrap"><div id="chat-area"></div></div>
<form id="send-message-area">
<p>Your message: </p>
<textarea id="sendie" maxlength = '100' ></textarea>
</form>
</div>

You can use the innerHTML and outerHTML property like the following way:
const div = document.createElement("div");
div.style.position = "absolute";
div.style.left = "0px";
div.style.top = "0px";
div.style.width = "240px";
div.style.height = "auto";
div.style.background = "red";
div.style.padding = "15px 0px 0px 0px";
div.style.color = "white";
div.id = "chat";
//
div.innerHTML += document.getElementById('page-wrap').outerHTML;
document.getElementById('page-wrap').remove(); // remove the previous one;
document.body.append(div);
<div id="page-wrap">
<h2>Chat</h2>
<p id="name-area"></p>
<div id="chat-wrap"><div id="chat-area"></div></div>
<form id="send-message-area">
<p>Your message: </p>
<textarea id="sendie" maxlength = '100' ></textarea>
</form>
</div>

Given that you already created your divElement, you will just need to get the div in your Html using either id/class etc... example :
var htmlDiv = document.getElementById('chat-area')
And then you would simply append your created div as so :
htmlDiv.append(myCreatedDiv)

Use appendChild method to add element into another (pure JavaScript)
div = document.createElement("div");
div2 = document.createElement("div");
div.appendChild(div2);
Alternative is jQuery's append as yahya mentioned, which uses the appendChild method internally.

Related

Element appending with and without scroll varies

I have 2 button, one in top another in the bottom. when I click the top button it works fine. when i scroll down to bottom button and click the button again ( same function ) it appends the element with some where. I am calculating the top position from absolute way. getting the relation ship with body.
so how to handle this kind of scenario?
Live demo
Js code :
const h1All = document.getElementsByTagName("h1");
function addElement() {
let div = document.createElement('div');
div.innerText = "I am here";
div.style.border = "1px solid green";
div.style.position = "absolute";
let h1 = h1All[0];
h1.style.border = "1px solid red";
let parentPos = h1.getBoundingClientRect();
console.log(parentPos)
document.body.appendChild(div);
div.style.top = parentPos.y + parentPos.height + "px";
}
HTML:
<h1>Hello Plunker!</h1>
<div class="mydiv">some div info goes here
<button onclick="addElement()">Click Me </button> //works fine.
</div>
<button onclick="addElement()">Click Me </button> //it's not. after scroll down!!
the second button appends the element some where. what is the correct way to calculation do we have to do here?
Thanks in advance.
const h1All = document.getElementsByTagName("h1");
function addElement() {
let div = document.createElement('div');
div.innerText = "I am here";
div.style.border = "1px solid green";
div.style.position = "absolute";
let h1 = h1All[0];
h1.style.border = "1px solid red";
let parentPos = h1.getBoundingClientRect();
document.body.appendChild(div);
div.style.top = parentPos.y + parentPos.height + "px";
}
.mydiv{
border: 1px solid green;
height: 600px;
}
<h1>Hello Plunker!</h1>
<div class="mydiv">some div info goes here
<button onclick="addElement()">Click Me </button>
</div>
<button onclick="addElement()">Click Me </button>
If you want absolute positioning, you need to take scrolling into account. You can do that with window.scrollY. Notice the change at the last line of addElement:
const h1All = document.getElementsByTagName("h1");
function addElement() {
let div = document.createElement('div');
div.innerText = "I am here";
div.style.border = "1px solid green";
div.style.position = "absolute";
let h1 = h1All[0];
h1.style.border = "1px solid red";
let parentPos = h1.getBoundingClientRect();
document.body.appendChild(div);
div.style.top = parentPos.y + parentPos.height + window.scrollY + "px";
}
.mydiv{
border: 1px solid green;
height: 600px;
}
<h1>Hello Plunker!</h1>
<div class="mydiv">some div info goes here
<button onclick="addElement()">Click Me </button>
</div>
<button onclick="addElement()">Click Me </button>

Add style with JavaScript

I am trying to set CSS styles using Javascript.
I have written this code:
<div class="dim" id="dim" title="Event">
</div>
<div class="dialog_wrapper" id="dialog_wrapper">
<div class="dialog" id="dialog"><img id="buyukresim" src="http://ginger-mum.com/wp-content/uploads/2015/10/3633-1269758855-0da5042c33400a811a5d766be4579cb8.jpg" height="250"></div>
</div>
<script>
document.getElementById('buyukresim').style.display = "none";
document.getElementById('dim').style.display = "none";
document.getElementById('dialog_wrapper').style.display = "none";
document.getElementById('dialog').style.display = "none";
function karanlikyap2() {
var ogedim = document.getElementById('dim');
var ogewrapper = document.getElementById('dialog_wrapper');
var ogedialog = document.getElementById('dialog');
var ogeresim = document.getElementById('buyukresim');
ogedim.style.height = "100%";
ogedim.style.width = "100%";
ogedim.style.position = "fixed";
ogedim.style.left = "0";
ogedim.style.top = "0";
ogedim.style.z-index = "1 !important";
ogedim.style.background-color = "black";
ogedim.style.filter = "alpha(opacity=75)";
ogedim.style.-khtml-opacity = "0.75";
ogedim.style.-moz-opacity = "0.75";
ogedim.style.opacity = "0.75";
ogedim.style.display = "block";
ogewrapper.style.width = "100%";
ogewrapper.style.top = "0";
ogewrapper.style.left = "0";
ogewrapper.style.position = "absolute";
ogewrapper.style.z-index = "5";
ogewrapper.style.display = "block";
ogedialog.style.width = "400";
ogedialog.style.height = "400";
ogedialog.style.margin = "0 auto";
ogedialog.style.padding = "40";
ogedialog.style.background-color = "#fff";
ogedialog.style.border = "1px solid #ccc";
ogedialog.style.color = "#333";
ogedialog.style.display = "block";
ogeresim.style.display = "block";
}
</script>
<button onclick="karanlikyap2()">Karanlık 2</button>
But the code is not working.
Note : I have a good French, but my English isn't good. Pardon me. I hope you understand.
What you are doing to alter the CSS is not a good way. Please look for references over the internet. In JS, it doesn't normally work the way you expect it to work. You are trying to change the CSS like you would normally do with CSS, but JS is a bit picky when it comes to CSS. For example to change background color, in CSS you would write "background-color", but in JS "background-color" would be "backgroundColor".
Only change the CSS from JS if absolutely necessary, use CSS class to style your element.
You can reference https://www.kirupa.com/html5/setting_css_styles_using_javascript.htm
But if you really want to do it this way, here it is how:
<div class="dim" id="dim" title="Event">
</div>
<div class="dialog_wrapper" id="dialog_wrapper">
<div class="dialog" id="dialog"><img id="buyukresim" src="http://ginger-mum.com/wp-content/uploads/2015/10/3633-1269758855-0da5042c33400a811a5d766be4579cb8.jpg" height="250"></div>
</div>
<button onclick="karanlikyap2()">Karanlık 2</button>
<script>
document.getElementById('buyukresim').style.display = "none";
document.getElementById('dim').style.display = "none";
document.getElementById('dialog_wrapper').style.display = "none";
document.getElementById('dialog').style.display = "none";
function karanlikyap2() {
var ogedim = document.getElementById('dim');
var ogewrapper = document.getElementById('dialog_wrapper');
var ogedialog = document.getElementById('dialog');
var ogeresim = document.getElementById('buyukresim');
ogedim.style.height = "100px";
ogedim.style.width = "100px";
ogedim.style.position = "fixed";
ogedim.style.left = "0";
ogedim.style.top = "0";
ogedim.style['z-index'] = "1 !important";
ogedim.style['background-color'] = "black";
ogedim.style.filter = "alpha(opacity=75)";
ogedim.style['-khtml-opacity'] = "0.75";
ogedim.style['-moz-opacity'] = "0.75";
ogedim.style.opacity = "0.75";
ogedim.style.display = "block";
ogewrapper.style.width = "100%";
ogewrapper.style.top = "0";
ogewrapper.style.left = "0";
ogewrapper.style.position = "absolute";
ogewrapper.style['z-index'] = "5";
ogewrapper.style.display = "block";
ogedialog.style.width = "400";
ogedialog.style.height = "400";
ogedialog.style.margin = "0 auto";
ogedialog.style.padding = "40";
ogedialog.style['background-color'] = "#fff";
ogedialog.style.border = "1px solid #ccc";
ogedialog.style.color = "#333";
ogedialog.style.display = "block";
ogeresim.style.display = "block";
}
</script>
As gavgrif hinted at in the comments, it would be better to define static CSS styles and then manipulate the class names instead of trying to set everything with JS. Only setting things at run-time when they need to be dynamic and changeable. This will help with the separation of concerns and help make your code more maintainable.
In this case everything you are defining is static, the only real change you are making is hiding or showing the elements via changing display to none or block. You can easily achieve a similar effect by instead just defining them as blocks and creating a class that hides an element via visibility: hidden. Then you can hide and show them by adding or removing that new class.
This is how I would rewrite it:
function karanlikyap2() {
var ogedim = document.getElementById('dim');
var ogewrapper = document.getElementById('dialog_wrapper');
// you only need to remove the hidden class from the items at the top
// level of the DOM, the wrapper and dim
ogedim.classList.remove('hidden');
ogewrapper.classList.remove('hidden');
}
function hide() {
var ogedim = document.getElementById('dim');
var ogewrapper = document.getElementById('dialog_wrapper');
// add the hidden class back on to hide them again.
ogedim.classList.add('hidden');
ogewrapper.classList.add('hidden');
}
// hide the dialog when something is clicked
document.getElementById('dialog_wrapper').addEventListener('click', hide, false);
document.getElementById('dim').addEventListener('click', hide, false);
#dim {
height: 100%;
width: 100%;
position: fixed;
left: 0;
top: 0;
z-index: 1 !important;
background-color: black;
filter: alpha(opacity=75);
-khtml-opacity: 0.75;
-moz-opacity: 0.75;
opacity: 0.75;
display: block;
}
#dialog_wrapper {
width: 100%;
top: 0;
left: 0;
position: absolute;
z-index: 5;
display: block;
}
#dialog {
width: 400px;
height: 400px;
margin: 0 auto;
padding: 40px;
background-color: #fff;
border: 1px solid #ccc;
color: #333;
display: block;
}
.hidden {
visibility: hidden;
}
<div class="dim hidden" id="dim" title="Event">
</div>
<div class="dialog_wrapper hidden" id="dialog_wrapper">
<div class="dialog" id="dialog">
<img id="buyukresim" src="https://lorempixel.com/output/cats-q-c-250-250-4.jpg" height="250">
</div>
</div>
<button onclick="karanlikyap2()">Karanlık 2</button>
(I've used a different image to get around mixed-content issues because StackOverflow is served over https and your image is on http.)
Further reading:
more information about classList
Séparation du fond et de la forme

Javascript : add images in div upon selecting value from select box

I am trying too add image inside dynamically created div. When user create go button it should create div element and image inside it according to value selected in select box. I have created div tag dynamically and created image object in order to get image. but in my code image is not loading inside div. can anyone help me to figure out issue ?
CSS
<style>
body{
background-image: url("final_images/back.jpg");
}
.container{
/*width: 600px;*/
/*height: 200px;*/
border:inset;
margin-top: 100px;
margin-left: 300px;
margin-right: 190px;
background-color:rgba(255, 234, 134, 0.9);
}
#selectBox{
margin-left: 210px;
width: 160px;
}
#holder {
width: 300px;
height: 300px;
background-color: #ffffff;
}
</style>
HTML
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div class = 'container' id="main">
<form name="myForm">
<select name="mySelect" id="selectBox">
<option value="womens">Women's coat</option>
<option value="mens">Men's coat</option>
<option value="kids">Kid's toys</option>
<option value="mixture">Classic mixture</option>
<option value="earing">Gold Earing</option>
</select>
<INPUT TYPE="button" VALUE="Go" id="go">
</INPUT>
</form>
<HR size="4" color="red" id="hr">
<!-- <div id="holder"> </div> -->
</div>
</body>
</html>
Javascript
<script>
imageObj = new Image(128, 128);
// set image list
images = new Array();
images[0]="final_images/wcoat.jpg";
images[1]="final_images/wcoat.jpg";
var go = document.getElementById('go');
go.addEventListener("click", loadItem);
function loadItem() {
var mainDiv = document.getElementById("main");
var btnPre = document.createElement("input");
//Assign different attributes to the element.
btnPre.type = "button";
btnPre.value = "previous";
btnPre.id = "preBtn";
mainDiv.appendChild(btnPre);
newdiv = document.createElement('div'); //create a div
newdiv.id = 'holder';
mainDiv.appendChild(newdiv); //add an id
var btnNxt = document.createElement("input");
//Assign different attributes to the element.
btnNxt.type = "button";
btnNxt.value = "next";
btnNxt.id = "nxtBtn";
mainDiv.appendChild(btnNxt);
var holder = document.getElementById("holder");
if(document.getElementById('selectBox').value == "womens"){
holder.src = images[0] + " Women's coat";
}
else if(document.getElementById('selectBox').value == "mens"){
holder.src = images[1] + " Men's coat";
}
}
</script>
A div is not an image container. Replace with img in the createElement fixes this.
Another big problem is the margins you use.
I've made a few adjustments
replaced margin-left with float: right for the select
put margin auto for left and right on the box.
imageObj = new Image(128, 128);
// set image list
images = new Array();
images[0] = "final_images/wcoat.jpg";
images[1] = "final_images/wcoat.jpg";
var go = document.getElementById('go');
go.addEventListener("click", loadItem);
function loadItem() {
var mainDiv = document.getElementById("main");
var btnPre = document.createElement("input");
//Assign different attributes to the element.
btnPre.type = "button";
btnPre.value = "previous";
btnPre.id = "preBtn";
mainDiv.appendChild(btnPre);
newdiv = document.createElement('img'); //create a div
newdiv.id = 'holder';
mainDiv.appendChild(newdiv); //add an id
var btnNxt = document.createElement("input");
//Assign different attributes to the element.
btnNxt.type = "button";
btnNxt.value = "next";
btnNxt.id = "nxtBtn";
mainDiv.appendChild(btnNxt);
var holder = document.getElementById("holder");
if (document.getElementById('selectBox').value == "womens") {
holder.src = images[0] + " Women's coat";
} else if (document.getElementById('selectBox').value == "mens") {
holder.src = images[1] + " Men's coat";
}
}
body {
background-image: url("final_images/back.jpg");
}
* {
box-sizing: border-box;
}
.container {
width: 400px;
border: inset;
margin-top: 100px;
margin-left: auto;
margin-right: auto;
background-color: rgba(255, 234, 134, 0.9);
}
#selectBox {
float: right;
width: 160px;
}
#holder {
width: 300px;
height: 300px;
background-color: #ffffff;
}
<div class='container' id="main">
<form name="myForm">
<select name="mySelect" id="selectBox">
<option value="womens">Women's coat</option>
<option value="mens">Men's coat</option>
<option value="kids">Kid's toys</option>
<option value="mixture">Classic mixture</option>
<option value="earing">Gold Earing</option>
</select>
<INPUT TYPE="button" VALUE="Go" id="go">
</INPUT>
</form>
<HR size="4" color="red" id="hr" />
<!-- <div id="holder"> </div> -->
</div>
You need to use an image tag instead of a div. You could also load images with CSS but thats probably not what you want.
starting on this line:
var holder = document.getElementById("holder");
var image = new Image(128, 128);
if (document.getElementById('selectBox').value == "womens") {
image.src = images[0];
holder.appendChild(image);
holder.appendChild(document.createTextNode(" Women's coat"));
} else if (document.getElementById('selectBox').value == "mens") {
image.src = images[1];
holder.appendChild(image);
holder.appendChild(document.createTextNode(" Men's coat"));
}
Let me elaborate.
In the JavaScript code you are creating a div element here
newdiv = document.createElement('div'); //create a div
newdiv.id = 'holder';
mainDiv.appendChild(newdiv);
and then you are searching for element with Id holder and setting new image url.
var holder = document.getElementById("holder");
// holder is <div></div> element
if (document.getElementById('selectBox').value == "womens") {
holder.src = images[0] + " Women's coat";
} else if (document.getElementById('selectBox').value == "mens") {
holder.src = images[1] + " Men's coat";
}
holder is a div tag now. it has no src attribute
But div element do not have attribute with name src. so the above code will just add one more attribute to your div tag. but browser will not interpret it.
So if you want load image by setting src attribute, then you probably have to create holder as img tag which has attribute src. like this.
newdiv = document.createElement('img'); //create a img
newdiv.id = 'holder';
mainDiv.appendChild(newdiv);
holder is a img tag. now it has src attribute
now it will work with no problem.

How to close custom made prompt box in javascript?

I'm trying to make a custom prompt box in javascript. However, I just can't figure out how to close it again. The cancel button does work (the prompt box disappears), but when you click on the ok button, the box doesn't disappear.
Since I based my code on the code on this page: https://www.developphp.com/video/JavaScript/Custom-Prompt-Box-Programming-Tutorial
But now I see that if I copy the example on that page, the OK button doesn't work either. Can someone tell me what's wrong?
This is the example on the site I linked to, which doesn't work:
<!DOCTYPE html>
<html>
<head>
<style>
#dialogoverlay{
display: none;
opacity: .8;
position: fixed;
top: 0px;
left: 0px;
background: #FFF;
width: 100%;
z-index: 10;
}
#dialogbox{
display: none;
position: fixed;
background: #000;
border-radius:7px;
width:550px;
z-index: 10;
}
#dialogbox > div{ background:#FFF; margin:8px; }
#dialogbox > div > #dialogboxhead{ background: #666; font-size:19px; padding:10px; color:#CCC; }
#dialogbox > div > #dialogboxbody{ background:#333; padding:20px; color:#FFF; }
#dialogbox > div > #dialogboxfoot{ background: #666; padding:10px; text-align:right; }
</style>
<script>
function changeText(val){
document.getElementById('status').innerHTML = val;
}
function doStuff(val){
document.body.style.background = val;
}
function CustomAlert(){
this.render = function(dialog){
var winW = window.innerWidth;
var winH = window.innerHeight;
var dialogoverlay = document.getElementById('dialogoverlay');
var dialogbox = document.getElementById('dialogbox');
dialogoverlay.style.display = "block";
dialogoverlay.style.height = winH+"px";
dialogbox.style.left = (winW/2) - (550 * .5)+"px";
dialogbox.style.top = "100px";
dialogbox.style.display = "block";
document.getElementById('dialogboxhead').innerHTML = "Acknowledge This Message";
document.getElementById('dialogboxbody').innerHTML = dialog;
document.getElementById('dialogboxfoot').innerHTML = '<button onclick="Alert.ok()">OK</button>';
}
this.ok = function(){
document.getElementById('dialogbox').style.display = "none";
document.getElementById('dialogoverlay').style.display = "none";
}
}
var Alert = new CustomAlert();
function CustomConfirm(){
this.render = function(dialog,op,id){
var winW = window.innerWidth;
var winH = window.innerHeight;
var dialogoverlay = document.getElementById('dialogoverlay');
var dialogbox = document.getElementById('dialogbox');
dialogoverlay.style.display = "block";
dialogoverlay.style.height = winH+"px";
dialogbox.style.left = (winW/2) - (550 * .5)+"px";
dialogbox.style.top = "100px";
dialogbox.style.display = "block";
document.getElementById('dialogboxhead').innerHTML = "Confirm that action";
document.getElementById('dialogboxbody').innerHTML = dialog;
document.getElementById('dialogboxfoot').innerHTML = '<button onclick="Confirm.yes(\''+op+'\',\''+id+'\')">Yes</button> <button onclick="Confirm.no()">No</button>';
}
this.no = function(){
document.getElementById('dialogbox').style.display = "none";
document.getElementById('dialogoverlay').style.display = "none";
}
this.yes = function(op,id){
if(op == "delete_post"){
deletePost(id);
}
document.getElementById('dialogbox').style.display = "none";
document.getElementById('dialogoverlay').style.display = "none";
}
}
var Confirm = new CustomConfirm();
function CustomPrompt(){
this.render = function(dialog,func){
var winW = window.innerWidth;
var winH = window.innerHeight;
var dialogoverlay = document.getElementById('dialogoverlay');
var dialogbox = document.getElementById('dialogbox');
dialogoverlay.style.display = "block";
dialogoverlay.style.height = winH+"px";
dialogbox.style.left = (winW/2) - (550 * .5)+"px";
dialogbox.style.top = "100px";
dialogbox.style.display = "block";
document.getElementById('dialogboxhead').innerHTML = "A value is required";
document.getElementById('dialogboxbody').innerHTML = dialog;
document.getElementById('dialogboxbody').innerHTML += '<br><input id="prompt_value1">';
document.getElementById('dialogboxfoot').innerHTML = '<button onclick="Prompt.ok(\''+func+'\')">OK</button> <button onclick="Prompt.cancel()">Cancel</button>';
}
this.cancel = function(){
document.getElementById('dialogbox').style.display = "none";
document.getElementById('dialogoverlay').style.display = "none";
}
this.ok = function(func){
var prompt_value1 = document.getElementById('prompt_value1').value;
window[func](prompt_value1);
document.getElementById('dialogbox').style.display = "none";
document.getElementById('dialogoverlay').style.display = "none";
}
}
var Prompt = new CustomPrompt();
</script>
</head>
<body>
<div id="dialogoverlay"></div>
<div id="dialogbox">
<div>
<div id="dialogboxhead"></div>
<div id="dialogboxbody"></div>
<div id="dialogboxfoot"></div>
</div>
</div>
<h1>My web document content ...</h1>
<h2>My web document content ...</h2>
<button onclick="alert('You look very pretty today.')">Default Alert</button>
<button onclick="Alert.render('You look very pretty today.')">Custom Alert</button>
<button onclick="Prompt.render('And you also smell very nice.')">Custom Alert 2</button>
<h3>My web document content ...</h3>
</body>
</html>
You're missing the second parameter for the ok button click, which allows you to invoke a function once you click ok:
<button onclick="Prompt.render('And you also smell very nice.', 'doStuff')">Custom Alert 2</button>
This will invoke doStuff with the value from the prompt.
There is one possibility check with the id's used for elements in you the code provided if at all there are duplicate id the javaScript will not work properly.
This statement in the code,
document.getElementById('dialogbox').style.display = "none";
Is making use of element with id 'dialogbox' so if at all there is another element in your page having same id. your code will not work properly. More help can be provided if there is code with problem is shared.

Problem with innerXhtml and onclick attribute

In the XHTML page i have this div:
<div id="listAzioni">
<h4 style="margin-bottom:3px;">List shape :</h4>
</div>
Subsequently incorporated within the div an input element via javascript using the library innerXhtml.
var paper = document.getElementById("listAzioni");
var toWrite = "<h4 style=\"margin-bottom:3px\">List shape :</h4>";
toWrite += "<input type=\"button\" class=\"listButton\" value=\""+id+"\" onclick=\"showAction('"+id+"');\"/>"+'<br/>';
innerXHTML(paper,toWrite);
But after adding the input element has no onclick attribute. I tried so hard but I have not found anything that would solve my problem. Where am I doing wrong?
Which browsers have you tried?
I suggest you to use standard DOM APIs, I write your code as below:
<html>
<head>
<style type="text/css">
.button {
border: 1px solid black;
padding: 3px;
}
</style>
<script type='text/javascript'>
function addButton() {
var container = document.getElementById('container');
if (container != null && container != undefined) {
var child = document.createElement("div");
var button = document.createElement("input");
button.value = "Click to alert";
button.type = "button";
child.style.padding = "10px";
child.style.border = "2px solid red";
button.className = "button";
button.onclick = showAlert;
child.appendChild(button);
container.appendChild(child);
}
}
function showAlert() {
alert("you clicked the button!");
}
</script>
</head>
<body>
<div id="container"></div>
<input value="add div and button" type='button' onclick='addButton();'/>
</body>
</html>

Categories

Resources