Adding div dynamically using href link - javascript

I'm trying to add a div dynamically using an link and some javascript. I've set up a jsfiddle http://jsfiddle.net/W4Sup/1654/.
Here's the html
Add Div
Here's the css
div {
border: 1px dotted red;
padding: 10px;
}
And here is the javascript:
var iDiv = document.createElement('div');
iDiv.id = 'block';
iDiv.className = 'block';
document.getElementsByTagName('body')[0].appendChild(iDiv);
iDiv.innerHTML = "I'm the first div";
// Now create and append to iDiv
var innerDiv = document.createElement('div');
innerDiv.className = 'block-2';
// The variable iDiv is still good... Just append to it.
iDiv.appendChild(innerDiv);
innerDiv.innerHTML = "I'm the inner div";
function addDiv() {
var newDiv = document.createElement('div');
newDiv.className = 'block-3';
iDiv.appendChild(newDiv);
newDiv.innerHTML = "Another inner div";
}
Can someone explain what I've got wrong please

check this updated fiddle, basically addDiv was not visible to the click event handler since it was not in a global scope (since it is inside domready event handler)
<script>
var addDiv;
</script>
addDiv = function addDiv() {
var newDiv = document.createElement('div');
newDiv.className = 'block-3';
iDiv.appendChild(newDiv);
newDiv.innerHTML = "Another inner div";
return false;
}

Well first of all you dont need the href, only the onclick will matter, thus making it usable on any html tag, not only <a>'s
Add Div
the onclick doesnt take a ; at the end of your function, it's an assignation, you'not calling it

I prefer the assign-in-the-JS approach. Set your event listener in your JS by grabbing that link and putting addDiv in its click event handler.
Demo using your code
Basic changes -
JS:
document.getElementById("joe").addEventListener("click", addDiv, false);
...
function addDiv( event ) {
event.preventDefault();
...
}
HTML:
Add Div
You don't have to use an ID, it was just the most convenient way in this example. I recommend it though if that's an option for you.

Related

Add div onclick with javascript

I am completely new to Javascript (and Stack Overflow) and I want to build a blog that allows the user to create a div onclick. I referenced this article on w3shool and tried all the three methods listed. However, the div doesn't show up when I use the first two methods and appears without clicking when I use the third one.
Here's my code for the third method:
HTML
<button class="box4" id="newEntry">NEW</button>
Javascript
const parent = document.getElementById("entries");
document.getElementById("newEntry").addEventListener("click", newEntry);
function newEntry() {
var newDiv = document.createElement("div");
parent.appendChild(newDiv);
}
For the second method, I replaced line 2 with
document.getElementById("newEntry").onclick= function () {newEntry()};
I have seen similar questions, but none of them solved my problem, so I would really appreciate your help.
There's nothing wrong with you code.
It works fine.
just one thing you have to remember: Div by default have no height, so if you want make sure to visualize it, just add height and color to it, like the code bellow.
const parent = document.getElementById("entries");
parent.style.width = '150px';
parent.style.height = '150px';
parent.style.backgroundColor = 'red';
document.getElementById("newEntry").addEventListener("click", newEntry);
function newEntry() {
var newDiv = document.createElement("div");
newDiv.style.width = '50px';
newDiv.style.height = '50px';
newDiv.textContent = 'Entry';
newDiv.style.backgroundColor = 'white';
parent.appendChild(newDiv);
}
<div id="entries"></div>
<button id="newEntry">new Entry</button>
Here is an example:
You can use querySelectorAll with a css selector to query all the elements matching the selector, but you can use the getElementByName too. In your example you query the elements by ID, but I don't se where you set the ids.
function onInitClick(){
const buttons = document.querySelectorAll('button');
const secondButton = buttons[1];
secondButton.addEventListener('click', createButtonAndAppend);
secondButton.innerText = 'Click me';
}
function createButtonAndAppend(){
const button = document.createElement('button');
button.addEventListener('click', createButtonAndAppend);
button.innerText = 'Adds another button';
document.body.append(button);
}
<button onclick="onInitClick();">Add click to second button</button> <button>Nothing happens</button>
you can do it simply using jquery.
if you want to add something to div,
$("#your_div_id").html("your child element")
for example
<div id="example"></div>
$("#example").html("<h1>Hello world</h1>")
then result is
<div id="example"><h1>Hello world</h1></div>

Adding events and functions on elements generated with createElement()

I created different elements-paragraphs with createElement()/createTextNode() and added them to the body.
My problem is that i want to make those divs links or be able to add events such as onclick and obviously there is no HTML code to do that..just javascript generated objects.
my code atm:
for (i=0; i<10; i++){
var newDiv = document.createElement("div");
newDiv.className = "block";
var heading = document.createElement("h2");
var newContent = document.createTextNode(data[1][i]);
heading.className="title";
heading.appendChild(newContent);
newDiv.appendChild(heading);
var paragraph = document.createElement("p");
var newContent2 = document.createTextNode(data[2][i]);
paragraph.className="light";
paragraph.appendChild(newContent2);
newDiv.appendChild(paragraph);
var currentDiv = document.getElementById("div1");
document.body.insertBefore(newDiv, currentDiv);
}
You can add the event listener to the object you just created. The object does not have to be HTML. Read more about adding event listeners and see simple example:
var someDiv = document.createElement('div');
var txt = document.createTextNode('click me');
someDiv.append(txt);
document.body.append(someDiv);
var myFancyFunction = function() {
alert('you clicked me');
};
someDiv.addEventListener('click', myFancyFunction);
Update after your code you can add an event listener to those objects you create on the fly. You can also add different functions on the same event. In this case it's the same function for both elements/objects .. play with this: (I changed the data to "dummy data" as there was no data)
var myClick = function(event) {
alert(event.target.innerHTML);
};
for (i=0; i<10; i++){
var newDiv = document.createElement("div");
newDiv.className = "block";
var heading = document.createElement("h2");
var newContent = document.createTextNode('dummy data1 index: ' + i);
heading.className="title";
heading.appendChild(newContent);
newDiv.appendChild(heading);
var paragraph = document.createElement("p");
var newContent2 = document.createTextNode('dummy data2 index: ' + i);
paragraph.className="light";
paragraph.appendChild(newContent2);
newDiv.appendChild(paragraph);
var currentDiv = document.getElementById("div1");
document.body.insertBefore(newDiv, currentDiv);
heading.addEventListener('click', myClick);
paragraph.addEventListener('click', myClick);
}
You can simply call addEventListener on the JS-generated objects, even before they are inserted into the DOM, or are never inserted at all:
let div = document.createElement('div');
div.addEventListener('click', function(event) {
// do something
});
// This will trigger a call of the registered click callback,
// regardless of whether the div is in the DOM:
div.dispatchEvent(new Event('click', {
"bubbles": true,
"cancelable": false,
}));
// To add it to the DOM, simply add it the way you wish:
document.body.appendChild(div);
EventTarget.dispatchEvent allows you to trigger an event in a computational way (has equivalent effect to actually clicking the div)
Do take note of the browser compatibility of the event constructor in the example above.
Once an element is added to the dom, you can select it just like any other element.
// Create the element
var paragraph = document.createElement('p');
// Give it an `id`
paragraph.id = 'foo';
// Add the element to the `dom`
document.body.appendChild(paragraph);
// Add the listener
paragraph.addEventListener('click', function() {
this.innerHTML = 'It was clicked';
});
p {
height:20px;
padding:10px;
outline:1px solid #bada55;
}
In the example above, I added an id. If for some reason you need to re-select the element it may make it easier.

Changing JavaScript into jQuery - createElement

I'm trying to use the draggable and resizable jQuery function, but I may have to change a little bit of this code to jQuery.
I have this HTML code:
<div id="resizable2" class="ui-widget-content">
<h3 class="ui-widget-header">MS</h3>
</div>
This works great with the jQuery:
$(function() {
$( "#resizable" ).draggable();
$( "#resizable" ).resizable();
}
But then, I've tried to use it with a div created by javascript:
function addnewbox() {
var newDiv = document.createElement("div");
var h = document.createElement("h3");
var text = document.createTextNode("MS");
document.body.appendChild(newDiv);
newDiv.appendChild(h);
newDiv.className = "ui-widget-content";
h.appendChild(text);
h.className = "ui-widget-header";
newDiv.id = "resizable";
}
And it's not working
Change your dom object to a jQuery object by calling $(newdiv) and re-initialise the resizable and draggable functionality on the new content.
function addnewbox() {
var newDiv = document.createElement("div");
var h = document.createElement("h3");
var text = document.createTextNode("MS");
newDiv.appendChild(h);
newDiv.className = "ui-widget-content";
h.appendChild(text);
h.className = "ui-widget-header";
newDiv.id = "resizable";
$(newDiv).resizable(); //Add this
$(newDiv).draggable(); //and this
document.body.appendChild(newDiv); //Append to the dom once you've finished with it.
}
As devqon has mentioned, the reason for this is that this function adds dynamic content (content which isn't there on page load) this means that the draggable and resizable functionality is not present on this new content. This is why you need to re-initialise the connection between the new element and the functionality.
Also as menioned don't re-use ID's, they must be unique. It is bad practice to use the same id for multiple elements and will very likely lead to other issues.
Lastly, it is a good idea when creating new content to manipulate it first and add it to the page at the end. In this instance you are appending further content inside the newly created div. I would do this first and then when finished with it, add it to the page.
Hi I have changed your function to:
function addnewbox() {
var newDiv = document.createElement("div");
var h = document.createElement("h3");
var text = document.createTextNode("MS");
newDiv.id = "resizable";
newDiv.className = "ui-widget-content";
h.className = "ui-widget-header";
h.appendChild(text);
newDiv.appendChild(h);
document.body.appendChild(newDiv);
}
And I have created a jsfiddle for you to try yourself:
http://jsfiddle.net/ttw7218z/4/
Well you need to initialize resiazble plugin on new DOM elements. You already have a few JS solutions so I will post one more version using jQuery for elements creation:
function addnewbox() {
$('<div class="ui-widget-content resizable">' +
'<h3 class="ui-widget-header">MS</h3>' +
'</div>').appendTo('body').resizable();
}
One more thin you should be aware of: you should not duplicate ids, they must be unique. So instead of multiple #resizable use .resizable classes.

How to create dynamic div in javascript without using jquery?

I want to make dynamic division on button click on my web page please tell me easiest solution, I am new to JavaScript.
Hope this will help
function divcreate() {
var div = document.createElement("div");
div.setAttribute("id", "mydiv");
div.className = "mdiv";
div.style.display = "none";
document.body.appendChild(div);
}
To create an element, use the createElement method
var mydiv = document.createElement('div');
//mydiv is a variable containing a newly created div
<button onclick="createDiv()">Click Me</button>
function createDiv(){
var newDiv = document.createElement('div');
}
//create a div like below
var div=document.createElement("div");
var node=document.createTextNode("This is new.");
div.appendChild(node);
Then append the above div to which you want it to be child
var element=document.getElementById("some_parent_tag");
element.appendChild(div);

How do I add a div to a page using javascript?

So... I want to add the following right before the /body of a document, I can't seem to find a way to make it work:
document.body.innerHTML+="<div style=\"position:absolute; right:-10px; bottom:10px;\">response</div>\"");
Especially with the <body> element, you shouldn't be using innerHTML to append elements to an element. An easier way is with DOM methods like createElement, insertBefore or appendChild.
https://developer.mozilla.org/en-US/docs/DOM/document.createElement
https://developer.mozilla.org/en-US/docs/DOM/Node.insertBefore
https://developer.mozilla.org/en-US/docs/DOM/Node.appendChild
Try this:
var div = document.createElement("div");
div.style.position = "absolute";
div.style.right = "-10px";
div.style.bottom = "10px";
div.innerHTML = "response";
var lastChild = document.body.lastChild;
document.body.insertBefore(div, lastChild.nextSibling);
Although I guess it would make sense to just append it to the body:
document.body.appendChild(div);
(instead of the last two lines in my first example)
It also depends on when you're calling this code. Of course it will work if executed in the middle of the <body>, but you probably want to wait until the body (DOM) is ready so that the element is actually appended at the real end of the body. By using something like:
window.onload = function () {
// Your code from above
};
This will make sure the original <body> contents are ready.
Don't add stuff like that! Instead, do this:
var newDiv = document.createElement('div')
newDiv.style.position = 'absolute'
newDiv.id = 'myDiv'
newDiv.innerHTML = 'hello'
//etc.
document.body.appendChild(newDiv)
Change code to
document.body.innerHTML="<div style=\"position:absolute; right:-10px; bottom:10px;\">response</div>\"";
Remove ) at the end
What about:
var div = document.createElement("div");
// it's better use a CSS here instead
div.style.position = "absolute";
div.style.right = "-10px";
div.style.bottom = "10px";
div.innerHTML = "response";
document.body.appendChild(div);
?

Categories

Resources