Add and remove div from body in javascript - javascript

I'm kinda new to javascript, and probably there are other people who already asked similar question, but I hope you can help me anyway.
I'm trying a simple basic operation of add/remove of a div.
The add works fine, the remove is never called.
function $(el) {
return document.getElementById(el);
}
function remove() {
console.log("remove called");
var child = $('second');
}
function addContainer() {
console.log("addContainer called");
var aContainer = document.createElement('div');
aContainer.setAttribute('id', 'second');
aContainer.innerHTML = "second";
document.body.appendChild(aContainer);
}
In the addContainer I try to add the onclick function callback, but apparently it doesn't work.
Here the jsfiddle of reference
http://jsfiddle.net/m8kyav2b/
DO you know why
1- the remove function is never called?
2- once I click on the remove link, the innerHTML is removed, but not the div "second"?
Thanks a lot in advance

Try it like this, it will work:
DEMO
function $(el) {
return document.getElementById(el);
}
function removeit() {
alert("remove called");
var child = $('second');
child.remove();
}
function addContainer() {
console.log("addContainer called");
var aContainer = document.createElement('div');
aContainer.setAttribute('id', 'second');
aContainer.innerHTML = "second";
document.body.appendChild(aContainer);
}
SIDENOTE:
Calling remove() as your function won't work as it is a native javascript function.
You didn't actually remove the div in your function, too!

Here is a helpful link: Remove element by id. The below code is tested and works (it will upon mouse over delete the HTML tag, so basically just change the syntax around a little to have it delete what ever tag you want.
<p id="el" onmouseover="remove()">test</p> <!--we are deleting with JavaScript this HTML <p> tag. -->
function remove() {
var element = document.getElementById("el"); /* finding and assigning element to variable element */
document
element.parentNode.removeChild(el); // then deleting the parent and child (please refer to link)
}
as far as the rest of your question. Look here: add onclick event to newly added element in javascript.

remove is never called because remove in your <a> tag is referring to the native function remove (to be specific, HTMLAnchorElement.prototype.remove/ChildNode.remove) instead of yours. This is why only the text is removed, since ChildNode.remove targets its child.
To reference your function, do
Or even better:
var aContainer = document.createElement('div'),
anchor = document.createElement("a");
aContainer.setAttribute('id', 'second');
a.innerText = "second";
a.addEventListener("click", remove);
aContainer.appendChild(a);
document.body.appendChild(aContainer);

Related

JavaScript-How can I add an onClick function to a dynamically created button element?

Beginner programmer here-I am making an app that generates list items with a dynamically created button as a child of the 'li' element. I want to assign an onClick function to this dynamically created button but nothing seems to work. I have tried many ways, here is my most recent code.
var done = document.createElement("button");
done.onClick=function() {
alert("working");
};
done.innerText = "Finished!";
done.id = "deleteButton_";
The button generates fine but nothing happens when clicked. Any ideas? Thanks!
case matters
done.onClick=function() {
needs to be
done.onclick=function() {
better if you use addEventListener and not all browsers support innerText look into textContent
For use addEventListener, you could do something like
done.addEventListener('click', function (){
alert('working');
});
var iDiv = document.createElement('div');
iDiv.id = 'buttonDiv';
var button= document.getElementById('buttonDiv').innerHtml('<input type="button" onclick="myFunction(this)"');
function myFunction(button){
console.log(buton.id);
alert('pressed button with id :'+button.id);
}

onmouseenter / onmouseleave In a JavaScript Library

I want to build a JS library, so I am not using any jQuery. This is Pure JavaScript.
I created a div after mouse entered the specific element then display some info inside the div just created and after mouse leave, the info will disappear.
The mouse enter part worked fine, it showed with correct text and css style, but when moving mouse out, it only run the function first time. the created div will stay there ignoring the mouseleave function after first try.
Here is the JS code
document.getElementById(id).addEventListener("mouseenter", function(){
var elemDiv = document.createElement('div');
elemDiv.id ="demo";
document.body.appendChild(elemDiv);
elemDiv.innerHTML = "something";
}, false);
document.getElementById(id).addEventListener("mouseleave", function(){
document.getElementById("demo").innerHTML="";
}, false);
I have tried the other method before, it gives same result
document.getElementById(id).onmouseenter = function(){...}
document.getElementById(id).onmouseleave = function(){...}
On every "mouseenter" you create a new element but you never delete it. On "mouseleave" you only delete the content of the first one, the second (third, ...) is still there and keeps its content.
You should probably create the element outside the event handlers and only change "innerHTML". Or you remove it on "mouseLeave" from the DOM.
You are creating multiple elements with the same ID and then querying with document.getElementById. This has unpredictable browser results (typically the first is returned) - you need to ensure that for each ID in your DOM, only one ID is present.
With that in mind, your mouseenter function is actually broken as it is creating extra copies of the same div when it needs to determine if one already exists.
document.getElementById(id).addEventListener("mouseenter", function(){
// Find the 'demo' div
var elemDiv = document.getElementById('demo');
// If it doesn't exist, create a div, give it the unique ID 'demo' and add it to the DOM'
if (!elemDiv) {
elemDiv = document.createElement('div');
elemDiv.id = 'demo';
document.body.appendChild(elemDiv);
}
// Whether it was already on the DOM or had to be created, the text is reset.
elemDiv.innerHTML = "something";
}, false);
See my JSFiddle for a complete example: http://jsfiddle.net/ckned3mx/6/
On every mouseenter event you are making a new element with the same id="demo" which is invalid HTML (ID should be unique).
Then on mouseleave the .getElementById() function will return the first element found with that ID, which is the one created by the first mouseenter.
This means you end up with multiple demo elements that don't get cleaned up.
You should either re-use the same element (don't create it if it already exists) or remove the element on mouseleave.
here is a Demo:
http://jsfiddle.net/hxzgpdoz/
i made some changes in your mouseenter event function:
var elemDiv = document.getElementById("demo");
if( elemDiv ){
elemDiv.innerHTML = "something";
}else{
elemDiv = document.createElement('div');
elemDiv.id ="demo";
document.body.appendChild(elemDiv);
elemDiv.innerHTML = "something";
}

Creating an element that can remove it self?

I'm building a lightbox as a school project, and I can't use jQuery. I've got an image. When you click it, Javascript makes a transparent div with the ID "overlay". I want the div to remove itself, or the parent to remove it but it doesn't work. I think it has to do with the fact that you can't link 'onclick' to an element that doesn't exists yet.
You have to remove the element from the parent. Something like this:
d = document.getElementById('overlay');
d.parentNode.removeChild(d);
Or you could just hide it:
d.style.display = 'none';
And, oh: you can add Javascript code to a (newly created) element by assigning a function to the onclick attribute.
d = document.createElement('div');
d.onclick = function(e) { this.parentNode.removeChild(this) };
You can remove the element like the following
var el = document.getElementById('div-02');
el.remove(); // Removes the div with the 'div-02' id
Click here for more details
Don't use the onclick handler in the tag, use Javascripts event functions such as addEventListener to dynamically add the event to the elements. You should also make sure that when you remove the elements you properly clean up all your references (in other words, unregister the event handlers).
I've got it :)
I was doing it like bart sad, but it didn't work. my code looked something like this:
image.onclick = function(){ *create overlay*};
overlay.oncklick = function() {*overlay.parentNode.removeChild(overlay)*};
the browser goes like wtf? cause it reads the code and thinks "i cant check if the user clicked a non-existing element."
So I did this:
image.onclick = function(){
*create overlay*
overlay.onclick = function() {*remove overlay*};
};

how to remove all ClientEvents from anchors in an HTML String with jQuery

I've been struggling with what seems to be a simple problem for a few hours now. I've written a REGEX expression that works however I was hoping for a more elegant approach for dealing with the HTML. The string would be passed in to the function, rather than dealing with the content directly in the page. After looking at many examples I feel like I must be doing something wrong. I'm attempting to take a string and clean it of client Events before saving it to our Database, I thought jQuery would be perfect for this.
I Want:
Some random text click here and a link with any event type
//to become:
Some random text click here and a link with any event type
Here's my code
function RemoveEvilScripts(){
var myDiv = $('<div>').html('testing this Do it! out');
//remove all the different types of events
$(myDiv).find('a').unbind();
return $(myDiv).html();
}
My results are, the onClick remains in the anchor tag.
Here's a pure Javascript solution that removes any attribute from any DOM element (and its children) that starts with "on":
function cleanHandlers(el) {
// only do DOM elements
if (!('tagName' in el)) return;
// attributes is a live node map, so don't increment
// the counter when removing the current node
var a = el.attributes;
for (var i = 0; i < a.length; ) {
if (a[i].name.match(/^on/i)) {
el.removeAttribute(a[i].name);
} else {
++i;
}
}
// recursively test the children
var child = el.firstChild;
while (child) {
cleanHandlers(child);
child = child.nextSibling;
}
}
cleanHandlers(document.body);​
working demo at http://jsfiddle.net/alnitak/dqV5k/
unbind() doesn't work because you are using inline onclick event handler. If you were binding your click event using jquery/javascript the you can unbind the event using unbind(). To remove any inline events you can just use removeAttr('onclick')
$('a').click(function(){ //<-- bound using script
alert('clicked');
$('a').unbind(); //<-- will unbind all events that aren't inline on all anchors once one link is clicked
});
http://jsfiddle.net/LZgjF/1/
I ended up with this solution, which removes all events on any item.
function RemoveEvilScripts(){
var myDiv = $('<div>').html('testing this Do it! out');
//remove all the different types of events
$(myDiv)
.find('*')
.removeAttr('onload')
.removeAttr('onunload')
.removeAttr('onblur')
.removeAttr('onchange')
.removeAttr('onfocus')
.removeAttr('onreset')
.removeAttr('onselect')
.removeAttr('onsubmit')
.removeAttr('onabort')
.removeAttr('onkeydown')
.removeAttr('onkeypress')
.removeAttr('onkeyup')
.removeAttr('onclick')
.removeAttr('ondblclick')
.removeAttr('onmousedown')
.removeAttr('onmousemove')
.removeAttr('onmouseout')
.removeAttr('onmouseover')
.removeAttr('onmouseup');
return $(myDiv).html();
}

jQuery Clone Recursion

Why is this "copy"(click) wrong, it binds all the previous handlers as well:
var add = function(element) {
var ele = element.clone(true);
$('.container').append(ele);
$('.copy', new).click(function(){ add(ele); });
}
Idea: I want to have an element text next to a "copy" button.
When I click "copy", it clones the current row and append it to the container.
But this seems to be recursive...
The true parameter says:
Normally, any event handlers bound to the original element are not copied to the clone. The optional withDataAndEvents parameter allows us to change this behavior, and to instead make copies of all of the event handlers as well, bound to the new copy of the element.
So you keep adding click event handlers to the .clone element. Depending on your actual case, just don't bind the event handler again:
var add = function(element) {
var cloned = element.clone(true);
$('.container').append(cloned);
}
$('.container .copy').click(function(){
add($(this).closest('tr'));
});
(I used $(this).closest('tr') to get the parent row. Obviously you have to adjust it to your needs.)
Update:
Or don't pass true:
var add = function(element) {
var cloned = element.clone();
$('.container').append(cloned);
$('.copy', cloned).click(function(){ add(cloned); });
}
new is JS keyword. Change it to something else and it should work.
( Your code does not have call of add() except of from itself. So it is not clear how code gets there initially. And recursive declaration of functions as in your code is a path to programmers hell )

Categories