JQuery cloned div not responding to click event

The goal is to expand the div to cover the entire screen without ruining the layout.

My current solution looks basically like this:

$( ".box" ).click(function() {
    copy = $(this).clone();
    copy.addClass("box-active");
    // save .box position + size     
    // maximize div
}

$( ".box-active" ).click(function() {
    // minimize div to saved .box position + size
    $(this).remove();
}

      

But cloned divs will not respond to click events. Is there a way to get around this?

Full code: http://codepen.io/deuxtan/pen/oXQpRy

+3


source to share


4 answers


Use event delegation for dynamically generated class in DoM elements



$(".container").on('click', '.box-active', function() {
  if(isFullscreen){ 
    d.width = "100px";
    d.height = "100px";            
    d.top = 0;            
    d.left = 0; 

    $(this).animate(d, duration);
    isFullscreen = false;
  }
});

      

+4


source


You need to use .on

for dynamically added elements.



$( ".container").on("click", ".box-active", function() {
    // ... minimize div ...
    $(this).remove();
});

      

+2


source


In your code, you have applied the coick event to one element, when you clone it, you are not cloning its events.

This is why you need to attach the event on all divs with class .box-active '.

$('#parent-of-boxes').on('click', '.box-active', function() {
 ...
});

      

It also works if you apply it on a document, but it's better to mark it minimalist to add it to the parent block.

Using the function will on

apply it to all elements added to the DOM that are inside#parent-of-boxes

+1


source


If you want to continue using the "clone", you need to include the boolean parameter "withDataAndEvents" in your call. This is incorrect by default.

So when you write it like

copy = $(this).clone();

      

you allow the default to be passed false

, and no data or events are included in the closure. You need to pass explicitly true

.

copy = $(this).clone(true);

      

For reference, here is the documentation for the clone method.

+1


source







All Articles