4

When I click on this button, I want the value to change. When I do it, at first it changes the text on button, but the map does not appear. after that, I repeat the process and the code works fine.

function change() {
  var elem = document.getElementById("myButton1");
  if (elem.value == "Show") elem.value = "Hide";
  else elem.value = "Show";
}



function displayMap() {
  if (document.getElementById('map').style.display == "none") {
    document.getElementById('map').style.display = "block";
    initialize();
  } else {
    document.getElementById('map').style.display = "none";
  }

}
#map {
  display: none;
}
<input onclick='change(), displayMap()' type='button' value='Show' id='myButton1'></input>
<div id="map" style="width:100%; height:300px;">map</div>
Ramesh Rajendran
  • 37,412
  • 45
  • 153
  • 234

2 Answers2

3

Assign document.getElementById('map').style.display = "none"; globally

Please try this below code

    document.getElementById('map').style.display = "none";// this line is the solution 
    function change() {
      var elem = document.getElementById("myButton1");
      if (elem.value == "Show") elem.value = "Hide";
      else elem.value = "Show";           
    }
    function displayMap() {
      if (document.getElementById('map').style.display === "none")       {
        document.getElementById('map').style.display = "block";
       } else {
        document.getElementById('map').style.display = "none";
       }
    }

   

   
 #map {
      display: none;
    }
 <input onclick='change(), displayMap()' type='button' value='Show' id='myButton1'></input>
    <div id="map" style="width:100%; height:300px;">map</div>

Note: Don't forgot to call your initialize() function which is removed from my snippet

Ramesh Rajendran
  • 37,412
  • 45
  • 153
  • 234
0

HTMLElement.style returns the inline style (what is listed in the style attribute).

You could use Window.getComputedStyle() like this:

var map = document.getElementById('map'),
  btn = document.getElementById("myButton1");

function change() {
  if (btn.value == "Show") btn.value = "Hide";
  else btn.value = "Show";
}

function displayMap() {

  var style = window.getComputedStyle(map);

  if (style.display == "none") {

    map.style.display = "block";

    initialize();

  } else {

    map.style.display = "none";
    
    console.log('hiding');

  }

}


// Placeholder
function initialize() {
  console.log('showing map');
}
#map {
  display: none;
  width: 100%;
  height: 300px;
  background:#333;
}
<input onclick='change(), displayMap()' type='button' value='Show' id='myButton1' />
<div id="map"></div>

Above method is fine, but I would a more consistent method such as a CSS class, and I would initialize the map in the first place because the way you implemented exhausts the initialize()

Adam Azad
  • 11,171
  • 5
  • 29
  • 70