1

I have a search input that populates suggestions in a div below it while the user is typing and I'd like to add an event listener to the suggestion div. The problem is when the page loads the suggestion div isn't populated with anything because the user hasn't typed anything in the search input yet and it throws

TypeError: searchSugg is undefined

Is there a way around this? I tried wrapping the listener in if (searchSugg !== undefined) {...} and though it doesn't throw an error it also doesn't run the addEventListener function.

Code:

    var searchSugg = document.getElementsByClassName('mapboxgl-ctrl-geocoder--suggestion')[0];  
    searchSugg.addEventListener('click', function() {
        // // Create variables to use in isochrone API
        var urlBase = 'https://api.mapbox.com/isochrone/v1/mapbox/';
        var lng = geocoder.mapMarker._lngLat.lng;
        var lat = geocoder.mapMarker._lngLat.lat;
        var profile = 'cycling';
        var minutes = 10;
        // Create a function that sets up the Isochrone API query then makes an Ajax call
            var query = urlBase + profile + '/' + lng + ',' + lat + '?contours_minutes=' + minutes + '&polygons=true&access_token=' + mapboxgl.accessToken;
                    $.ajax({
                    method: 'GET',
                    url: query
                    }).done(function(data) {
                        map.getSource('iso').setData(data);
                    })
        map.addSource('iso', {
            type: 'geojson',
            data: {
            'type': 'FeatureCollection',
            'features': []
            }
        });
        map.addLayer({
            'id': 'isoLayer',
            'type': 'fill',
            // Use "iso" as the data source for this layer
            'source': 'iso',
            'layout': {},
            'paint': {
            // The fill color for the layer is set to a light purple
            'fill-color': '#5a3fc0',
            'fill-opacity': 0.3
            }
        }, "poi-label");
    });
prime90
  • 653
  • 9
  • 16

1 Answers1

0

You can check if searchSugg exists before assigning the click handler.

let searchSugg = document.getElementsByClassName("some-class-that-does-not-exist")[0];

searchSugg && searchSugg.addEventListener('click', event => {
  // click event handler code
});

// Or you can do
if (searchSugg) {
  searchSugg.addEventListener('click', event => {
    // click event handler code
  });
}
<p>Some Webpage</p>
Matt Oestreich
  • 6,430
  • 2
  • 12
  • 33