Search code examples
javascriptbuttonactionvargetelementbyid

action-btn needs two clicks to perform the click


var button = document.getElementById("action-btn");

button.addEventListener("click", function(){
    var container = document.getElementById("mostrarc");
        
    if(container.style.display === "none") {
        container.style.display = "block"
    } else {
        container.style.display = "none";
    }
});

need to click twice for the function to happen

the purpose of this button is that when clicking a new div will appear, I would like to change the title of the button after clicking


Solution

  • Most likely it has to do with the initial state of the container element. As I mentioned in the comments, avoid setting the style property and instead use CSS classes, which makes the JS code so much simpler.

    // Get your DOM references just once, not every time a function runs.
    var button = document.getElementById("action-btn");
    var container1 = document.getElementById("mostrarc1");
    var container2 = document.getElementById("mostrarc2");
    
    button.addEventListener("click", function(){
      // Just toggle the use of the class which removes the need for if/then
      container1.classList.toggle("hidden");
      container2.classList.toggle("hidden");
    });
    #mostrarc1 {
      width:75px; height:75px; background: #e0e0e0; margin:25px;
    }
    #mostrarc2 {
      width:75px; height:75px; background: #ff0; margin:25px;
    }
    
    /* This class is applied in the HTML so the element will initially be hidden.
       But, when the button is clicked, the use of the class will be toggled.  */
    .hidden { display:none; }
    <button type="button" id="action-btn">Show/Hide</button>
    <div id="mostrarc1" class="hidden">Container Area 2</div>
    <div id="mostrarc2">Container Area 1</div>