I have a simple template setup that looks like this:
<script id="entry" type="text/x-handlebars-template">
<p>Some content</p>
<h2>Language Select:</h2>
<button type="button" class="btn btn-primary">English</button>
<h2>Ready:</h2>
<button type="button" id="play" class="btn btn-success">Play</button>
<button type="button" id="stop" class="btn btn-danger">Stop</button>
</script>
However, also in my document I have a script with the following content:
var playButton = document.querySelector('#play');
playButton.addEventListener('click', function (e) {
sendMessage('Cue', 'Play');
}, false);
Most of the time, (but not always) because of the async nature of javascript, this returns:
Uncaught TypeError: Cannot read property 'addEventListener' of null
If I wrap that code in a setTimeout
of some amount, it will always work.
Can someone please explain to me the best way to add event listeners from scripts to generated template content?
I looked at this answer but it seems like the way they suggest is just to add a delay before adding the event listener.
Sorry, forget my previous answer.
You need render template for first, then insert this html to body...
var source = document.querySelector("#some-template").innerHTML;
var template = Handlebars.compile(source);
document.body.innerHTML = template();
and then add listeners...
http://jsfiddle.net/jwrae0n2/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With