Emil Orol
Emil Orol

Reputation: 561

Nested click in jQuery

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

Answers (3)

Karl-Andr&#233; Gagnon
Karl-Andr&#233; Gagnon

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

MaKR
MaKR

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

amphetamachine
amphetamachine

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

Related Questions