0

I have map in my View.

On marker click I need to open pop-up and this is working fine.

Here is the code for it:

 export function  all_hotels_map_results(): void {
Helpers.set_currency_settings();
const json = gon.hotel_info;
const token = "***********";
const centerLatlng = new mapboxgl.LngLat(gon.destination_city.lng, gon.destination_city.lat);
mapboxgl.accessToken = token;
let map = new mapboxgl.Map({
      container: "map-canvas",
      style: "mapbox://styles/mapbox/streets-v9",
      center: centerLatlng,
      zoom: 9
});

map.addControl(new mapboxgl.NavigationControl());
map.on('load', function() {
$.each(json, function(i, item) {
  let myLatlng = new mapboxgl.LngLat(item.lng, item.lat);
  let stars = "";
  for(let s = 0; s < item.rating; s++) {
    stars += '<img class="star-image" style="height:20px;width:20px;">';
    }
  const Popup_Content = '<div class="map-card__wrapper">'
  +'<div class="map-card__image-container">'
  +'<div class="map-card__image" style="background: url('+item.pictures[0].url+');">' +'</div>'
  +'</div>'
  +'<div class ="map-card__content-container ">'
  + '<div class ="map-card__title">'+item.name +'</div>'
  +'<p class="map-card__address">'+item.address1+'</p>'
  + '<div class ="map-card__review">'+stars +'</div>'
  + '<div class ="map-card__price-container">'+__("Flygbolag")+ ": "+ accounting.formatMoney(item.sales_prices[0])
  +'</div>'
  + '</div>';

  let marker = new mapboxgl.Marker()
    .setLngLat(myLatlng)
    .setPopup(new mapboxgl.Popup({ offset: 5 })
    .setHTML(Popup_Content))
    .addTo(map);
  });
});

};

But I need to get value of <div class ="map-card__title"> and I am trying to do it like this:

$('.map-card__title').click(function(){
alert();


 })

But it does not work. I have no alert messages in console, anything.

Where can be my fault?

Thanks for your help.

Krishna Prashatt
  • 631
  • 9
  • 18
Balance
  • 121
  • 3
  • 13

1 Answers1

0

The elements to which you are attaching the event listeners are being generated dynamically.

It might happen that these elements were not even created or attached to the DOM when your $('selector').click(fn) was called.

You should try delegating the event to common parent of these elements like your Map itself or even the body. That way, your body or Map listens for the click on each of your children elements, and not these elements themselves.

What I suggest looks pretty much like this:

$('body').on('click', '.children', function() {});

You can read more about these here:

https://learn.jquery.com/events/event-delegation/

Rafael Mejía
  • 485
  • 4
  • 9