0

I have been trying to add my own custom on blur function to the search input field for a Mapbox map that is using the Mapbox GL JS WordPress plugin.

I have this code that I have added to my js file, but it only seems to work if I add it directly to the browser console. So my guess is I need to make it wait until some script has loaded.

$('.mapboxgl-ctrl input').on('blur', function() {
    console.log('blur');
});

I have tried wrapping it in this function so that it waits for the input field to be loaded:

$.when($('.mapboxgl-ctrl input')).then((self) => {
    console.log('input loaded');
    self.on('blur', function() {
        console.log('blur');
    });
});

I have also tried the following function that waits for a script to be loaded - Mapbox has a few different scripts and I have tried replacing the url with the different scripts, but still no luck.

$.getScript('https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v2.2.0/mapbox-gl-geocoder.min.js', function(){ 
    console.log('script loaded');
    $('.mapboxgl-ctrl input').on('blur', function() {
        console.log('blur');
    });
});

Does anyone have other suggestions for me to try? Or have achieved this in the past?

  • Can you try with one of the solutions in https://stackoverflow.com/questions/5525071/how-to-wait-until-an-element-exists ? Without binding the event handler yet, just using `console.log` to validate that you were able to obtain a reference to the DOM element for the search field. – Rafael Almeida Jun 26 '20 at 23:52
  • 1
    @RafaelAlmeida I couldn't get the first few to work. But this answer here was the one that worked for me https://stackoverflow.com/a/29754070/13593919 - So thank you for guiding me in the right direction! – kandi_galaxy Jun 28 '20 at 23:09

0 Answers0