JSFiddle - React, Tailwind, and code Playground
by Jammerwoch
HTML
<a id="init" href="#">Add buttons....</a><br><br>
<div id="container">
<div id="buttons">
</div>
<div id="dialogs">
</div>
</div>
CSS
.dialog {
border: solid 1px black;
margin: 14px 0;
padding: 4px;
display: none;
}
.dialog a.close {
display: inline-block;
float: right;
}
JavaScript
var $buttons = $('#buttons');
var $dialogs = $('#dialogs');
function addButtons( n ) {
var nButtons = $('#buttons a.open').length;
for( var i=nButtons+1; i<=nButtons+n; i++ ) {
$('<a class="open" href="#" data-id="' + i + '">tasty ' + i + '!</a> ' +
'<a class="openStupid" href="#" data-id="' + i + '">stupid ' + i + '!</a><br>')
.appendTo( $buttons );
$('<div class="dialog" data-id="' + i + '">dialog ' + i +
'<a href="#" class="close">[x]</a></div>')
.appendTo( $dialogs );
}
}
addButtons( 3 );
$('#init').on( 'click', function(evt) {
evt.preventDefault();
addButtons( 3 );
});
// we hook up the stupid buttons this way...it'll work for the first buttons,
// but not any added later:
$('a.openStupid').on( 'click', function(evt) {
evt.preventDefault();
id = $(this).data('id');
$dialog = $('div.dialog[data-id="' + id + '"]');
$dialog.toggle();
});
// we hook up the good buttons this way...it'll work no matter when the buttons
// are added (make sure you understand the difference!):
$('#container').on( 'click', 'a.open', function(evt) {
evt.preventDefault();
id = $(this).data('id');
$dialog = $('div.dialog[data-id="' + id + '"]');
$dialog.toggle();
});
// we hook up the dialog close buttons...this will always work because we've done
// it the smart way:
$('#container').on( 'click', 'a.close', function(evt) {
evt.preventDefault();
$dialog = $(this).closest('div.dialog');
$dialog.toggle();
});