Aymen Ragoubi
Aymen Ragoubi

Reputation: 396

Adding Event Listener on button - Javascript

I'm trying to add an event listener on button added dynamically to a google maps infowindow.

  var contentString = '<br></br>' +
    '<button type="button" class="btn btn-success" id="btnDirection">Get direction</button> </div>' +
     '<button type="button" class="btn btn-success" id="btnDiscount">Related discount</button> </div>';

  var marker = new google.maps.Marker({
         map: map,
         animation: google.maps.Animation.DROP,
         position: place.geometry.location,
         icon: './Google_Maps_Markers/darkgreen_MarkerK.png'
  });

  google.maps.event.addListener(marker, 'click', function() {
        infoWindow.setContent(contentString);
        infoWindow.open(map, this);

        var btn = $(contentString).filter('#btnDirection'); 
        if(btn != null){
             for(var i=0; i<btn.length; i++){
                  btn[i].addEventListener('click', function()           
                       { console.log("hello") });
             };
         };   
 });

Buttons are displayed on each infowindow, but when I click on nothing heppens.

Could someone help me with this ?

Upvotes: 1

Views: 3401

Answers (4)

Rahul R. Thakre
Rahul R. Thakre

Reputation: 1

if u will same id then event will file on all the button with same id,u should use different Id for each button.

Upvotes: 0

artemisian
artemisian

Reputation: 3106

One solution would be:

google.maps.event.addListener(marker, 'click', function() {
        infoWindow.setContent(contentString);
        infoWindow.open(map, this);

        $('#btnDirection').bind('click', function() {          
            console.log("hello direction") 
        }); 

        $('#btnDiscount').bind('click', function() {          
            console.log("hello discount") 
        }); 
 });

Full code:

 var contentString = '<br></br>' +
    '<button type="button" class="btn btn-success" id="btnDirection">Get direction</button> </div>' +
     '<button type="button" class="btn btn-success" id="btnDiscount">Related discount</button> </div>';

  var marker = new google.maps.Marker({
         map: map,
         animation: google.maps.Animation.DROP,
         icon: './Google_Maps_Markers/darkgreen_MarkerK.png'
  });

  var map;
  $(document).ready(function(){
      function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: -34.397, lng: 150.644},
          zoom: 8
        });
		var marker = new google.maps.Marker({
				 map: map,
				 animation: google.maps.Animation.DROP,
				 position: {lat: -34.397, lng: 150.644}
		  });
		  
		  var infoWindow = new google.maps.InfoWindow();
		  
		google.maps.event.addListener(marker, 'click', function() {
			infoWindow.setContent(contentString);
			infoWindow.open(map, this);

			$('#btnDirection').bind('click', function() {          
				alert("hello direction") 
			}); 

			$('#btnDiscount').bind('click', function() {          
				alert("hello discount") 
			}); 
		});
     }
	 
	 initMap();
});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script src="https://maps.googleapis.com/maps/api/js?libraries=geometry"></script>
</head>
<body>
	<div id="map" style="height:100vh;"></div>
</body>
</html>

Upvotes: 0

Koelli91
Koelli91

Reputation: 19

When dynamically adding content to the DOM (as the infoWindow-Content), you have to register the eventListener on a parent element that's existing prior to the event-binding (e.g. the body or the map-Container).

You can achieve this by doing the following:

google.maps.event.addListener(marker, 'click', function() {
    infoWindow.setContent(contentString);
    infoWindow.open(map, this);

    $('body').on('click', '#btnDirection', function() {
        console.log('Hello');
    });
});

The second one works but it's performing action with all buttons when I click on one of them since that I am adding buttons with the same id to infowindows. Do you know how can I fix this ?

IDs should be unique! Use classes for elements with the same use/meaning. Sorry for answering this question here, I can't add a comment on the main question (not enough reputation yet).

Upvotes: -1

geocodezip
geocodezip

Reputation: 161324

The content of the infowindow is added to the DOM asynchronously, so it can't be found until the InfoWindow "domready" event fires.

From that documentation):

domready | Arguments: None
This event is fired when the containing the InfoWindow's content is attached to the DOM. You may wish to monitor this event if you are building out your info window content dynamically.

To attach event listeners to those buttons, run the JQuery code to look for them in a 'domready' event listener:

google.maps.event.addListener(marker, 'click', function() {
  infoWindow.setContent(contentString);
  infoWindow.open(map, this);
  // wait for the infowindow's domready event
  google.maps.event.addListenerOnce(infoWindow, 'domready', function() {
    // find the elements with the "btn" class and add the click listener to the one with id="btnDirection"
    var btn = $(".btn").filter('#btnDirection');
    if (btn != null) {
      for (var i = 0; i < btn.length; i++) {
        btn[i].addEventListener('click', function() {
          console.log("hello")
        });
      };
    };
  });
});

proof of concept fiddle

code snippet:

var geocoder;
var map;

function initialize() {
  var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(37.4419, -122.1419),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  var infoWindow = new google.maps.InfoWindow();
  var contentString = '<div id="other"></div><br></br>' +
    '<button type="button" class="btn btn-success" id="btnDirection">Get direction</button> </div>' +
    '<button type="button" class="btn btn-success" id="btnDiscount">Related discount</button> </div>';

  var marker = new google.maps.Marker({
    map: map,
    animation: google.maps.Animation.DROP,
    position: map.getCenter(), // place.geometry.location,
  });

  google.maps.event.addListener(marker, 'click', function() {
    infoWindow.setContent(contentString);
    infoWindow.open(map, this);
    // wait for the infowindow's domready event
    google.maps.event.addListenerOnce(infoWindow, 'domready', function() {
      // find the elements with the "btn" class and add the click listener to the one with id="btnDirection"
      var btn = $(".btn").filter('#btnDirection');
      if (btn != null) {
        for (var i = 0; i < btn.length; i++) {
          btn[i].addEventListener('click', function() {
            document.getElementById("other").innerHTML = "Get Direction was CLICKED";
            console.log("hello")
          });
        };
      };
    });
  });
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>

Upvotes: 2

Related Questions