Reputation: 1425
Edit: added Handlebar template loading
I am trying to detect when a dynamically added element has been loaded (from a handlebars template), but the event never fires.
Here is the code:
var source = $('#mapTemplate').html();
var template = Handlebars.compile(source);
$('#wrapper').fadeOut(function() {
$('#wrapper').html(template());
$('#wrapper').fadeIn();
});
$('body').on('ready', '#mapCanvas', function() {
alert('Ready')
var mapOptions = {
center: new google.maps.LatLng(-34.397, 150.644),
zoom: 8
};
var map = new google.maps.Map(document.getElementById("mapCanvas"),mapOptions);
})
What am I doing wrong?
Upvotes: 1
Views: 1448
Reputation: 92324
Your template is available on the page immediately after the call to insert handlebar's template
$('#wrapper').html(template());
//#mapCanvas should be available
However, you're probably getting an error because you are telling the div to fade in and jQuery makes it invisible initially. Be sure to wait until the fadeIn
finishes.
var source = $('#mapTemplate').html();
var template = Handlebars.compile(source);
$('#wrapper').fadeOut(function() {
$('#wrapper').html(template());
$('#wrapper').fadeIn(function() {
var mapOptions = {
center: new google.maps.LatLng(-34.397, 150.644),
zoom: 8
};
var map = new google.maps.Map(document.getElementById("mapCanvas"),mapOptions);
});
});
Upvotes: 1
Reputation: 708056
As you have discovered, there is no "ready"
event when a template is loaded.
The usual solution to knowing when anything that is dynamically loaded is ready is to supply a completion callback function to the code that is doing the loading. When that callback is called, the content is available in the page. I don't know exactly how you're loading the handlebars template, but the handlebars functions I see for loading a template, all take a callback argument that is called after the template has been successfully loaded. You would then trigger your map
logic from within that callback.
If you show us the code you're using for loading the template, we can be much more specific.
Now, that you've shown us the code, your template is already preloaded and you can restructure you code like this to add the mapping stuff as soon as the fadeIn has finished:
var source = $('#mapTemplate').html();
var template = Handlebars.compile(source);
$('#wrapper').fadeOut(function() {
$('#wrapper').html(template()).fadeIn(function() {
var mapOptions = {
center: new google.maps.LatLng(-34.397, 150.644),
zoom: 8
};
var map = new google.maps.Map(document.getElementById("mapCanvas"),mapOptions);
});
});
Upvotes: 1