Reputation: 343
A div box with class .my-row
contain add and remove button with ID #add-row
and #remove-row
respectively. Jquery is used to clone div box on click over #add-row
button and to remove div box using #remove-row
button. I want fadein and fade-out animation while adding and removing div box.
HTML:
<div id="my-field">
<div class="grey-field">
//box i want to clone
<div class="my-row">
<a id ="add-row" class="button"></a>
<a id ="remove-row" class="button"></a>
</div>
</div>
</div>
jQuery
$('#add-row').on('click', function() {
var row = $('.my-row').clone(true);
row.removeClass('my-row');
row.insertBefore('#my-field .grey-field>div:last');
return false;
});
$('#remove-row').on('click', function() {
$(this).closest("div").fadeOut(600, function(){
$(this).remove();
});
return false;
});
Upvotes: 0
Views: 2497
Reputation: 12347
I posted my answer in this jsfiddle
$('.add-row').on('click', function() {
var row = $('.my-row').clone(true);
row.removeClass('my-row');
row.insertBefore('#my-field .grey-field>div:last').hide().fadeIn(600);
return false;
});
$('.remove-row').on('click', function() {
$(this).closest("div").fadeOut(600, function(){
$(this).remove();
});
return false;
});
I took the liberty to change your id reference to class identifier instead for the reason stated below from the jQuery API:
Note: Using .clone() has the side-effect of producing elements with duplicate id attributes, which are supposed to be unique. Where possible, it is recommended to avoid cloning elements with this attribute or using class attributes as identifiers instead.
Upvotes: 1
Reputation: 1672
js:
$('.add-row').on('click', function() {
var row = $(this).parent().clone(true);
row.removeClass('my-row').css('display','none'); // I suggest you don't remove the class here because you might need it later
row.insertBefore('#my-field .grey-field>div:last').fadeIn('slow'); // here you are inserting before the last element, maybe that's how you want it
return false;
});
$('.remove-row').on('click', function() {
$(this).parent().fadeOut(600, function(){
$(this).remove();
});
return false;
});
html:
<div id="my-field">
<div class="grey-field">
<!--box I want to clone -->
<div class="my-row">
<a class ="button add-row">11</a>
<a class ="button remove-row">22</a>
</div>
</div>
</div>
Upvotes: 1
Reputation: 1597
If I'm reading your question right, you want to fade-in anything with the ID, not class, add-row when you click on it and fade-out ID remove-row. ID's are denoted with a "#" while classes are denoted with a "." Check your HTML to be sure if it is a class or ID, because that may be why it's not working
Upvotes: 0