Reputation: 18237
hi I'm trying to add to button inside an info window an event i tried like this
var infoWindow = new google.maps.InfoWindow({
content: '<div></br><span class="formatText">Ubicacion del Marcador: </span>' + event.latLng.toString()
+ '</br> <input type="button" id="btnPrueba" value="prueba"/></div>'
});
google.maps.event.addListener(marker, 'click', function () {
infoWindow.open(map, this);
google.maps.event.addDomListener(document.getElementById('btnPrueba'), 'click', removeMarker);
});
function removeMarker(){
alert('it works');
}
What am i doing wrong? or it's another way to do this?. Thanks
Edit
I'm also tried with jquery like this but although the event it's get by the function the alert doesn't show. When i do the debug with chrome it's works :(
google.maps.event.addListener(marker, 'click', function () {
infoWindow.open(map, this);
$("#btnPrueba").click(function () {
alert('funciona');
});
});
Upvotes: 4
Views: 6738
Reputation: 834
Calling a global function like @DeeV's shown really does seem like the straightest shot at this (except for dirtying the global namespace a smidge which is looked down on these days). jQuery event delegation does work without any additional setTimeout gymnastics but feels like a heavier function call stack to accomplish the same goal. e.g.
$("#myMapContainer").on("click", "#btnPrueba", function() {alert "it works";});
However, sticking with the global approach, on top of @DeeV's answer, often the trick is getting some contextual values that you can act upon in that event handler:
var myMarkerArray = [];
function removeMarker(markerIndex) {
myMarkerArray[markerIndex].setMap(null);
}
for(int i=0; i<myLocationData.length; i++) {
var marker = new google.maps.Marker({...});
myMarkerArray.push(marker);
var popup = new google.maps.InfoWindow({ content: '<input type="button" id="btnPrueba" value="prueba" onclick="removeMarker('+i+')"/>' });
}
Upvotes: 1
Reputation: 28928
My workaround was to use a short timeout.
var infoWindow = ... (as in your question) ...
infoWindow.open(...);
setTimeout(function(){
$('#btnPrueba').on('click', function(e){
alert("It works at last!");
});
},50); //Wait for 0.05s
When I didn't use the setTimeout
wrapper it did not work. Even though setContent()
and open()
had already been called. I assume this means the creation is done asynchronously.
NOTE: the "50" is a magic number, so potentially brittle.
NOTE: using the following also did not work for me, which I still find strange and cannot explain:
$('#btnPrueba').on('click', document, function(e){
alert("No luck...");
});
Upvotes: 0
Reputation: 36035
Try the "onclick" attribute for the button.
'<input type="button" id="btnPrueba" value="prueba" onclick="removeMarker()"/>'
Upvotes: 6