Add div onclick with javascript - 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>

Related

Adding div dynamically using href link

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.

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.

Javascript - remove button and parent

Hi I am just learning Javascript and after following some tutorials I thought it would be nice to practise some Javascript by making stuff.
So now I am trying to make a very easy to-do-list. Just for practise, but I get stuck.
I managed to add items with a remove-button to an UL with JS. But, BUT:
How do I make it so; when you click on the removeMe button, that only that Li will be removed?
What should I use?
Here's my code:
var buttonAdd = document.getElementById('but1');
var buttonRemove = document.getElementById('but2');
var ul = document.getElementById('myUl');
function addLi() {
var newLi = document.createElement('li');
var removeThis = document.createElement('button');
var textInput = document.getElementById('inputText').value;
if(textInput === ""){
alert('Add text');
}else{
newLi.innerHTML = textInput;
newLi.appendChild(removeThis);
removeThis.innerHTML = "Remove me";
removeThis.setAttribute("onClick", "removeMe(this);");
ul.appendChild(newLi);
}
}
buttonAdd.onclick = function() {
addLi();
};
buttonRemove.onclick = function() {
ul.innerHTML = "";
};
function removeMe(item){
//get called when clicked on the remove button
}
and my HTML:
<body>
<ul id="myUl"></ul>
<input id="inputText" type="text"><br />
<button id="but1">Add stuff</button><br />
<button id="but2">Remove all</button>
</body>
Thanks
The function remove() is a brand new DOM 4 method and not very widely supported yet. The clunky, but bulletproof way would be:
function removeMe(item){
item.parentElement.parentElement.removeChild(item.parentElement);
}
or with a bit more elegance:
function removeMe(item){
var parent = item.parentElement;
parent.parentElement.removeChild(parent);
}
http://jsfiddle.net/BtbR4/
Also be careful with this:
removeThis.setAttribute("onClick", "removeMe(this);");
Handing a function reference as a string is always a bad idea for several reasons (eval'ing the string, messing up the scope). There are several better options:
removeThis.onclick = removeMe;
or if you need to hand over parameters
removeThis.onclick = function(){removeMe(your,parameters)};
The best option however is to attach eventhandlers always like this:
Element.addEventListener("type-of-event",functionReference);
You just need to remove the parent node (the li), as I've shown using jsbin.
function removeMe(item){
item.parentNode.remove();
}
Please note Blue Skies's comment that this may not work across all browsers, an alternative is:
var par = item.parentNode; par.parentNode.removeChild(par);
a cleaner way to do things is to add
removeThis.onclick = removeMe;
and
function removeMe(mouseEvent){
this.parentNode.remove();
}
This is consistent with how you add the other onclick functions in your code. Since you said you are learning js, it is a good idea to learn how events and functions work. So, the take away from this is that the 'this' of a function that is attached to an object is the object itself (the removeThis object in this case), and event handlers give you access to the event that invoked them (mouseEvent) in the argument list.
JSfiddle: http://jsfiddle.net/QT4E3/

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);
?

javascript choose what is going to include element

I have two elements, the first one is the default to print on screen
<input id=post-category value="first">
and the other is this, which will only show if some onclick was made and of course the first element must show off
<select id=cat-sel ><option>second</option></select>
UPDATED
I tried this code
el = document.getElementById("post-category");
el.style.visibility = "hidden";
el2 = document.getElementById("cat-sel");
el2.style.visibility = "visible";
but the problem here is, the 2nd element is indented. because it escapes the space for the 1st element. I don't like that, I wanted them to be on the same position
Change to
el = document.getElementById("post-category");
el.style.display = "none";
el2 = document.getElementById("cat-sel");
el2.style.display = "block";
since visible/hidden does not remove the space the element takes up on the page
You need to set display:none on the field you need to hide initially
Assuming a checkbox have
window.onload=function() {
document.getElementById("categoryCheckbox").onclick=function() {
var chk = this.checked;
document.getElementById("post-category").style.display = chk?"none":"block";
document.getElementById("cat-sel").style.display = chk?"block":"none";
}
}
PS: A little more code is needed for the show/hide to survive a reload by the way...
Define CSS for your ID's and fix the position.

Categories

Resources