I would like to clone the entire div with the button properties. Is there any problem with my current code $("#dynamicsegment").clone().appendTo("#copieddiv")?
<div id="dynamicsegment">
<button type="button" id="start">Star</button>
<button type="button" id="stop">Stop</button>
</div>
<script>
$('#start').click(function(){
$( "#stopdiv" ).hide();
$( "#startdiv" ).show();
});
$('#stop').click(function(){
$( "#stopdiv" ).show();
$( "#startdiv" ).hide();
});
</script>
CodePudding user response:
Here it is the code but I do not suggest to use id on cloned element because ID is unique.
$('#start').click(function(){
$( "#stopdiv" ).hide();
$( "#startdiv" ).show();
});
$('#stop').click(function(){
$( "#stopdiv" ).show();
$( "#startdiv" ).hide();
});
$('#button').on('click', function(){
$(".cloned-element:last").clone().appendTo(".cloned-element:last");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="cloned-element" id="dynamicsegment">
<button type="button" id="start">Star</button>
<button type="button" id="stop">Stop</button>
</div>
<button id="button">Dublicate</button>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
$('#start').click(function(){
$("#dynamicsegment").clone().appendTo('body');
$( "#stopdiv" ).hide();
$( "#startdiv" ).show();
});
$('#stop').click(function(){
$( "#stopdiv" ).show();
$( "#startdiv" ).hide();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="dynamicsegment">
<button type="button" id="start">Star</button>
<button type="button" id="stop">Stop</button>
</div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
The clone function copies all the properties (such as id, class, custom attribute) of the destination object. But its event handlers are not copied.
CodePudding user response:
Change your css ID's to classes. Also when you append your new element, check that it exists. In this example, I am assuming there is already a .cloned-elemnent
$(function(){
var $template = $('.dynamicsegment').clone()
$(template).appendTo(".cloned-element:last")
})
Let me know if this helps :)