Listen to parent Element
A way to listen to dynamic content, observing the parent element.
A Pen by Konstantinos Tsatsarounos on CodePen.
<div id="wrapper">
<button id="add-button">Add Button</button>
<div id="day-buttons">
<button class="day">Day 1</button>
<button class="day">Day 2</button>
<button class="day">Day 3</button>
</div>
<div class="print">
</div>
</div>
<script type="text/template" id="button-template">
<button class="day" >{{name}}</button>
</script>
var DayNumber = 3;
//Set an alias for querySelector
var _$ = function(selector){
return document.querySelector(selector);
};
function createButton(container){
var buttonTemplate = _$('#button-template');
var button = buttonTemplate.innerHTML.replace('{{name}}', 'Day '+ ++DayNumber);
container.innerHTML += button;
}
//Set variables
var buttonsContainer = _$('#day-buttons'),
addButton = _$('#add-button');
//Bind an event listener to the add button with the given values
addButton.addEventListener('click', createButton.bind(addButton, buttonsContainer));
//Bind the listener for everybutton
buttonsContainer.addEventListener('click', function(evt){
var button = evt.target;
if(button.getAttribute('class') == 'day'){
_$('.print').innerHTML = button.innerText;
}
});
html {
font-family: Ubuntu;
font-size: 16px;
}
button {
border: 0;
background-color: royalblue;
font-weight: bold;
font-size: 120%;
color: whitesmoke;
padding: 1em 2em;
cursor: pointer;
}
button:active {
box-shadow: inset 1px 1px 5px #3F4073;
}
button:hover,
button:focus {
background-color: #3756B5;
}
.print {
background: lightslategrey;
color: white;
height: 150px;
width: 500px;
margin-top: 2em;
}
#wrapper {
padding: 1em;
}
#add-button {
margin-bottom: 2em;
}