Reputation: 561
I have a DIV that when click on it, it will add another DIV inside itself. Then if I click the newly added DIV it will remove it.
HTML
<div id="container"></div>
jQuery
$('#container').on('click', function(e){
// Add other DIV
$( this ).append('<div class="other">XYZ</div>');
e.stopPropagation();
// Remove other DIV
$('div.other').bind('click', function(event){
$( this ).remove();
event.stopPropagation();
});
});
How efficient is this method if I plan to have to lot of child DIVs?
Upvotes: 0
Views: 4634
Reputation: 33870
It probably doesn't need any optimisation because it doesn't do a lot of thing. but if you want it to be optimal without using vanilla JS, I would go like this :
var $myDiv = $('<div class="other">XYZ</div>'); //Cache the div instead of creating it every click
$('#container').on('click', function(e){
if($myDiv.is(e.target)) //Check if your div is the clicked target
$myDiv.remove(); //Remove the div
else
$myDiv.appendTo(this) // Else append the div.
});
Just note that if the div
contain children element, the if
should be changed to :
if($(e.target).closest($myDiv).length)
Upvotes: 0
Reputation: 1892
I would slightly change the JQuery so you can chain off the selector for the .append, and use .on instead of .bind:
$('#container').on('click', function(e){
// Add other DIV
$( this ).append(
$('<div>').attr('class', 'other')
.html('XYZ')
// Remove other DIV
.on('click', function(event){
$( this ).remove();
event.stopPropagation();
});
)
e.stopPropagation();
});
It's untested code, but it should be functionally identical to yours. I would avoid binding on $(document) because it is inefficient due to firing events on the entire DOM. Parsing the DOM is the most time-consuming part of Javascript code execution, which is why reusing JQuery selectors as I just have is also more efficient.
Upvotes: 1
Reputation: 30595
Attaching events when another event fires will likely cause some unintentional side effects, and subject your DOM to memory leaks.
As a general rule, attach handlers once, run often.
$(document)
.on('click', '#container', function(e) {
// Add other DIV
$(this).append('<div class="other">XYZ</div>');
})
.on('click', 'div.other', function(e) {
$(this).remove();
e.stopPropagation();
});
Upvotes: 2