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.
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.
Share Improve this question edited May 23, 2017 at 12:33 CommunityBot 11 silver badge asked Jan 6, 2016 at 3:00 StartecStartec 13.3k28 gold badges110 silver badges170 bronze badges1 Answer
Reset to default 4Sorry, 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.pile(source);
document.body.innerHTML = template();
and then add listeners...
http://jsfiddle/jwrae0n2/