L.fcg L.fcg - 5 months ago 18
jQuery Question

Create a toggle button that changes text when layer is on and when layers is off

I have created this code that makes a toggle button that can switch layers on and off in a leaflet. Switching layers on and off works fine. But I also want the text in the toggle button to change. When a layer is on the leaflet map it has to say: "Layer on" and when there is no layer on the map it needs to say: "Layer off". I tried implementing

$(this).text(function(i, text){
return text == 'Layer off';
});


and

$(this).text(function(i, text){
return text == 'Layer on';
});


But it returned the text "false" in the button. This is the function I used:

$("#layerControl").click(function(event) {
layerClicked = window[event.target.value];
if (map.hasLayer(layerClicked)) {
map.removeLayer(layerClicked);
$(this).text(function(i, text) {
return text == 'Layer off';
});
} else {
map.addLayer(layerClicked);
$(this).text(function(i, text) {
return text == 'Layer on';
});
}
});

Answer

Rather than returning a boolean value, I suggest returning a string value conditionally, based on the current text content.

Below, I'm using a ternary operator to determine the new text.

$('button').on('click', function() {
  $('#output').text(function(i, text) {
    return text == 'Layer off' ? 'Layer on' : 'Layer off';
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button">CLICK ME</button>
<div id="output">Layer off</div>


Edit:

However, looking at the spirit and intent of your code, I might just set the appropriate text based on whether the layer is showing. Two separate conditions may just complicate things and introduce unexpected behavior.

$("#layerControl").click(function(event) {
  layerClicked = window[event.target.value];
  if (map.hasLayer(layerClicked)) {
    map.removeLayer(layerClicked);
    $(this).text('Layer Off');
  } else {
    map.addLayer(layerClicked);
    $(this).text('Layer On');
  }
});
Comments