'Mapbox - Cannot trigger marker click with "element".click() after clicking on map

I've currently implemented custom markers on the map using the following code:

// extend mapboxGL class so we can edit the click function
    class CustomMarker extends mapboxgl.Marker {
      // new method onClick, sets _handleClick to a function you pass in
      onClick(handleClick) {
        this._handleClick = handleClick;
        return this;
      }

      // the existing _onMapClick was there to trigger a popup
      // but we are hijacking it to run a function we define
      _onMapClick(e) {
        const targetElement = e.originalEvent.target;
        const element = this._element;

        if (this._handleClick && (targetElement === element || 
        element.contains((targetElement)))) {
          this._handleClick();
        }
      }
    };

    const el1 = document.createElement('div');
    el1.id = "marker1";                                                
    el1.style.marginTop = '-'+(36/2)+'px';
    // make a marker and add it to the map
    new CustomMarker(el1)
    .onClick(() => { //when clicked, define the following function
        console.log(1+1);
        })
        .addTo(map);

I have then added a html button to navigate between markers(i.e next and previous) which then calls something like document.getElementByID("marker1").click() once clicked.

This button works normally and triggers the marker click, however when I click on the mapbox map once (a single click anywhere on the map), document.getElementByID("marker1").click() does not seem to get called when I click the html button. If I drag the map or double click to zoom in after however, the html button starts to work again. Does anyone know why this is happening?



Solution 1:[1]

Something very confusing you have made. Actually MapBox Marker does not have click event, but its Element does. So to make things work, you need to use the following:

marker.getElement().addEventListener('click', function(event: PointerEvent) {
  event.stopPropagation(); // to prevent map click event from triggering as well
  ...
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alexander