Reputation: 3
This is my code:
<script>
$('#closeDiv').hide();
$('#addDiv').click(function (){
var $newdiv1 = $('<div id="main_content4"><br /><button class="close">Close this</button></p><p>Ajoutez une div avec jQuery. Cacher le bouton qui permet de l\'ajouter, ensuite ajoutez un bouton dans la nouvelle div pour la fermer à son tour. Pour finir on affiche à nouveau le bouton pour afficher la div.</p></div>'),
existingdiv1 = document.getElementById('main_content3');
$('#main').append($newdiv1);
$('#addDiv').hide();
$('#closeDiv').show();
});
$('#closeDiv').click(function() {
$('#main_content4').remove();
$('#addDiv').show();
$('#closeDiv').hide();
});
</script>
As you can see in my var $newdiv1
I create this button:
<button class="close">Close this</button>
But when I add this, it doesn't work:
$('#close').click(function() {
$('#main_content4').remove();
});
What's wrong with my code?
Upvotes: 0
Views: 1678
Reputation: 493
Your code is trying to attach event before the element has been created. To attach event to newly created element you need either directly attach it in same place where you create it, or use listeners like jQuery .on
.
Upvotes: 0
Reputation: 74420
Use delegation:
$('#main').on('click','.close',function() {
$('#main_content4').remove();
});
But wait, maybe no delagation is needed only your selector was wrong:
$('.close').click(function() {
$('#main_content4').remove();
});
Upvotes: 2