Santiago Santiago - 12 days ago 9
Javascript Question

Changing map address with jquery

I currently have this code, when user clicks on the div, the map on the changes the position with the updated addresss:

<div class="row">
<div class="col-sm-12 col-lg-6">
<div class="dir">
<h3 class="title">Shopping abasto</h3>
<p>tel: 4676-4565</p>
<p>Avenida Marota</p>
<div id="map" data-maps="Av. Aconquija 600, Paseo Heller, Yerba Buena, Tucuman"><span class="glyphicon glyphicon-map-marker" id="dir"></span></div>
</div>
<div class="dir">
<h3 class="title">Shopping abasto</h3>
<p>tel: 4676-4565</p>
<p>Avenida Marota</p>
<div id="map" data-maps="Juncal 1213, Buenos Aires, Argentina"><span class="glyphicon glyphicon-map-marker"></span></div>
</div>
<div class="dir">
<h3 class="title">Shopping abasto</h3>
<p>tel: 4676-4565</p>
<p>Avenida Marota</p>
<div id="map" data-maps="Paseo Pilar, Del Viso, Buenos Aires Province"><span class="glyphicon glyphicon-map-marker"></span></div>
</div>

</div>
<div class="col-sm-12 col-lg-6">
<div class="map">
<iframe width="100%" height="368" frameborder="0" style="border:0" src="https://www.google.com/maps/embed/v1/place?q=Buenos%20Aires%2C%20Argentina&key=AIzaSyCDg1Dfoxg3cKcOsucYZQnTjpmPjbUqe2M"></iframe>
</div>
<div class="col-separador-s"></div>
<div class="">
<img src="http://placehold.it/727x502">
</div>
</div>
</div>


I want the map to update the position when clicking on any of the divs with the id 'map'.
The problem is that it only works with the first div, here is my script so far:

jQuery(function(){
jQuery('#map').on('click', function() {
var maps = jQuery(this).data('maps');
jQuery('.map iframe').attr('src','https://www.google.com/maps/embed/v1/place?q=' + maps + '&key=AIzaSyCDg1Dfoxg3cKcOsucYZQnTjpmPjbUqe2M');
});
});

Answer

Element id's must be unique in the DOM for targeting to work as expected. There will not be errors thrown with the rendering of elements with the same ID, however it goes against standard practice, and introduces issues such as you're experiencing here.

Please refer to this article for a more in-depth differentiation between ID and CLASS.

So, to resolve the issue you're experiencing, you should make the following adjustments:

  1. Change map id div's from <div id="map"> to <div class="map">
  2. Change map class jQuery selector from jQuery('#map') to jQuery('.map')
  3. Change the iframe wrapping div to <div id="map-wrapper">
  4. Change jQuery selector for the iframe to jQuery('#map-wrapper iframe')