The goal is to expand a div to cover the whole screen without destroying 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 the cloned divs will not respond to click events. Is there a way to work around that?
Full code:
The goal is to expand a div to cover the whole screen without destroying 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 the cloned divs will not respond to click events. Is there a way to work around that?
Full code: http://codepen.io/deuxtan/pen/oXQpRy
Share Improve this question edited Jul 29, 2015 at 13:12 Deuxtan asked Jul 29, 2015 at 13:11 DeuxtanDeuxtan 537 bronze badges 04 Answers
Reset to default 4Use Event delegation for dynamically created 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;
}
});
You need to use .on
for dynamically added elements.
$( ".container").on("click", ".box-active", function() {
// ... minimize div ...
$(this).remove();
});
If you want to continue to use "clone", you need to include the "withDataAndEvents" boolean parameter in your call. By default it is false.
So when you write it as
copy = $(this).clone();
you are allowing the default value of false
to be passed, and no data or events is included in the close. You need to explicitly pass true
.
copy = $(this).clone(true);
For reference, here is the documentation for the clone method.
In your code you did applied coick event on one element, when clonning it, you are not cloning it's events.
That is why you need to attach an event on all div's with class '.box-active'.
$('#parent-of-boxes').on('click', '.box-active', function() {
...
});
This will also work if you apply it on the docuemnt, but it's better to keet it minimalistic as possible, so add it to boxes parent block.
Using on
function will apply it to all elements added to DOM that are inside #parent-of-boxes