Is it possible to add a simple show/hide button on the leaflet map which will allow the user to see the legend on choice?

Here is my code for the legend:

    var legend0 = L.control({});
        legend0.onAdd = function (map) {
    var div = L.DomUtil.create('div', 'info legend'),
    grades = ["Localisation", "Orientation"],
    labels = ["icon-gamze/location1-zoom1.png", "icon-gamze/location2-zoom1.png"];
     div.innerHTML += '<b>Localisation</b><br>' 
for (var i = 0; i < grades.length; i++) {
       div.innerHTML +=
       (" <img src="+ labels[i] +" height='20' width='20'>") + grades[i] +'<br>';

       return div;

  • You may achieve this quite easily using jquery .hide() and .show() methods, or using simple vanilla JS functions and CSS.
    – juminet
    Commented Mar 20, 2017 at 11:06
  • Thanks, but could you please exemplify? I'm quite new to the suite.
    – Gamze
    Commented Mar 20, 2017 at 11:12

1 Answer 1


For this, you need to write a few lines in Javascript. Many solutions exist, depending if you want to use JS and/or CSS frameworks or not. Here is below an example with jquery:

First, add a button somewhere in your page:

<button type="button" onclick="toggleLegend();">My button</button>

Then, in the function toggleLegend():

    showLegend = true;  // default value showing the legend

    var toggleLegend = function(){
        if(showLegend === true){
        /* use jquery to select your DOM elements that has the class 'legend' */
           showLegend = false; 
           showLegend = true; 

This target all the elements that have the class 'legend' of your page.

Have a look at e.g. https://stackoverflow.com/questions/21070101/show-hide-div-using-javascript#21070237 for a pure vanilla JS example of show/hide.


  • Thank you @juminet for your answer, but I unfortunately I could not make it work out. Can it be due to the fact that I have a number of legends on my map?
    – Gamze
    Commented Mar 20, 2017 at 17:19
  • Does it work at least for one legend? Did you include jquery in your page?
    – juminet
    Commented Mar 20, 2017 at 19:22
  • Yes, I included jquery. And, no I could not make it work for even one legend. @juminet
    – Gamze
    Commented Mar 21, 2017 at 9:42
  • there was an error in my code. Sorry, I hadn't try it before
    – juminet
    Commented Mar 21, 2017 at 9:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.