Creating an element that can remove it self? - javascript

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*};
};

Related

Javascript in AEMto add a class if a checkbox is clicked

I am trying to target a class called 'horizontal-video' in a div within an AEM component and if the author has clicked a checkbox that has an ID of 'coral-id-540' I want to add a second class called 'flipped' to the div. Here is the code I wrote that isn't working. Could someone help me figure out why it's not working? The console does not show errors.
var x = document.getElementsByClassName("horizontal-video");
$('#coral-id-540').change(function(){
if($(this).is(":checked")) {
$(this).addClass("flipped");
} else {
$(this).removeClass("flipped");
}
});
It's quite possible you're not waiting for the DOM to completely load, (or at least have this bit of code below the element in question on the page during page load)
Is your code wrapped in $(document).ready(function(){ //your code });?
Also, be aware that any element that is dynamically added to the page by JavaScript/jQuery after page load will not have a listener attached using the method you're using.
To allow dynamically added elements to be included in your listener, you should target an ancestor node and add the listener to that node. In plain English: attach the listener to a "higher up" element. The safest (although slowest) node being document itself, but it's better to target something closer:
$(document).ready(function () {
var $horizontalVideo = $(".horizontal-video"); //You're using jQuery - why not use it here? Also, I always name jQuery objects with a `$` in front as a shorthand to know it's wrapped in a jQuery object. Plus, a more descriptive name will help you immensely.
//replace parent-of-coral with the ID of a parent element that you know exists on DOM ready:
$("#parent-of-coral").on("change", "#coral-id-540", function (e) { //get used to using "e" as the event variable for preventing default / stopping propagation / etc
$this = $(this); //cache $(this) reference rather than creating another jQuery object each time you use it
if ($this.is(":checked")) {
$this.addClass("flipped");
} else {
$this.removeClass("flipped");
}
});
});

Add and remove div from body in 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);

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";
}

Dinammically button in jquery with window.open

I am trying to create a button dinnamically for adding a view before upload something to a database.
I am using jquery for my web, so if solution is in jquery, better.
Now I am trying a piece of code I found here: Creating Dynamic button with click event in javascript
This is how I adapted for my case:
var element = document.createElement("input");
//Assign different attributes to the element.
element.type = 'button';
element.value = 'hello'; // Really? You want the default value to be the type string?
element.name = 'HELLO'; // And the name too?
element.onclick = window.open('test.html?name=test&surname1=test2&surname2=test4', 'my_new_window');;
var foo = document.getElementById("registerButtonDiv");
//Append the element in page (in span).
foo.appendChild(element);
It adds the button (well, it is a simple button and not like the others in my webpage, I guess, something related to css)
But if I try to use something like I did about onclick event, it creates the button but don't add the onclick part. I tried changing quotes, not using them... many things so maybe now it is wrong. Don't take it so seriosuly, I just copy the latest version. With the alert on the example, it works fine.
What do I have to do to fix this?
I need to do this way because I have to pass some variables dinnamically filled to the other page and this is the simplest solution I found.
As onclick is an event, it needs a handler. And here you can handle the event using any handler which can serve you as your requirements.
element.onclick = function(){
window.open('test.html?name=test&surname1=test2&surname2=test4', 'my_new_window');
};
Demo
You need to pass a function reference to onclick:
element.onclick = function(){
window.open(...);
};
or using jquery:
var element = $('<input type="button" value="hello" name="HELLO">');
element.on('click', function() {
window.open('test.html?name=test&surname1=test2&surname2=test4', 'my_new_window');
});
$("#registerButtonDiv").append(element);
jsfiddle

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();
}

Categories