0

I'm having difficulty to find how to add a removeEventListener(). When i add addEventListener() it worked good but when i added removeEventListner to be able to remove my data on the map it didn't work. (I'm using leaflet)

Here's how i'm doing it:

var geodata ={{{jsonData}}};

var bouto = document.getElementById("bouton");

function jsoncalls(){
    L.geoJSON(geodata,{
    onEachFeature: onEachFeature
}).addTo(mymap);
}

bouto.addEventListener("click", jsoncalls);
bouto.removeEventListener("click", jsoncalls);

Thank you

jemiloii
  • 24,594
  • 7
  • 54
  • 83
  • What exactly are you trying to do here? When you call `removeEventListener` it removes the `click` handler you just added from `addEventListener`. – gen_Eric Jul 02 '19 at 15:50
  • Well, you are just removing an event listener, so you won't get any calls to your `jsoncalls` method when your button gets clicked anymore. Look into the library you are using for adding the data if you can remove it as well (feel free to add a tag to it, by using [edit] on your post) – Icepickle Jul 02 '19 at 15:51
  • You should edit the question with proper title and make it clearer you want the geoJSON results appear/disappear. This has nothing to do with removing event listeners....!!! – yezzz Jul 02 '19 at 17:15

1 Answers1

3

Looks like your removing the event listener immediately. Try removing it after the event has been called.

var geodata = {{{jsonData}}}; // <- noting this is unusual. guessing its sudo code

var bouto = document.getElementById("bouton");
var displayElement = document.getElementById("display"); // whatever your display data element is

function jsoncalls() {
    // I'm assuming you want to remove it after jsoncall() is called.
    bouto.removeEventListener("click", jsoncalls);
    bouto.addEventListener("click", hideData);

    L.geoJSON(geodata, {
        onEachFeature: onEachFeature
      })
      .addTo(mymap);

    // show your display element here
    displayElement.style.display = "block";
}

function hideData() {
    bouto.removeEventListener("click", hideData);
    bouto.addEventListener("click", jsoncalls);

    // hide your display element here
    displayElement.style.display = "none";
}

bouto.addEventListener("click", jsoncalls);

Here is a updated jsfiddle, it will show elements on odd clicks and hide on even clicks. https://jsfiddle.net/gmbnrx2q/

jemiloii
  • 24,594
  • 7
  • 54
  • 83