Creating an element that can remove it self?
Asked Answered
E

4

13

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.

Enjambment answered 27/3, 2013 at 0:49 Comment(2)
That's right, you can't. So set the hook after you append it to the body. Also your question would benefit from some code and examples of what you've tried, and exactly what is going wrong.Misgovern
Can you please post your current HTML output and Script please you use to create the overlay. Maybe we can add a setTimeout if you want to remove it automatically based on some passed amount of time if that is feasible or we can add an event to the parent element to remove it. It would make it much easier with the relevant code though.Shadbush
C
37

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) };
Cristionna answered 27/3, 2013 at 1:9 Comment(0)
K
6

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

Kaczmarek answered 9/7, 2018 at 7:15 Comment(0)
H
1

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).

Hamal answered 27/3, 2013 at 0:53 Comment(0)
E
0

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*};
};
Enjambment answered 27/3, 2013 at 11:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.