1

I have a div element in my page which I want to make visible only upon the click of a button. This works as expected, except the div promptly disappears again and I cannot get it to remain visible.

    function btnAddItem_Click() {
            document.getElementById("add-item-popup").style.display = "block"
        }
    .add-item-popup {
        width: 400px;
        height: 550px;
        display: none;
        background-color: #ededed;
        position: fixed;
        right: 40%;
        top: 20%;
    }
    <div class="add-item-popup" id="add-item-popup">
        //Contains a form
    </div>





    <button onclick="btnAddItem_Click()">Add Item</button>

6
  • can you please tell the results Commented Jan 17, 2020 at 13:35
  • @AhmedsaysReinstateMonica The div appears as expected for a second and then disappears again Commented Jan 17, 2020 at 13:36
  • Questions seeking code help must include the shortest code necessary to reproduce it in the question itself preferably in a Stack Snippet. See How to create a Minimal, Reproducible Example Commented Jan 17, 2020 at 13:37
  • as I have edited your question this is not happening. Check other libraies Commented Jan 17, 2020 at 13:38
  • @Brandon Holz you can use jquery slideToggle() function. Commented Jan 17, 2020 at 13:39

2 Answers 2

2

I'm going to make a reasonable assumption but an assumption nonetheless with this solution. The assumption is your <button> tag with your onclick handler is inside of another form. If so, replace this line here:

<button onclick="btnAddItem_Click()">Add Item</button>

To become this code:

<button type="button" onclick="btnAddItem_Click()">Add Item</button>

Explanation: When button is inside a form without type="button" specified, it will submit the form, and in your case, reload the page where the css then of course is anew. Thus you only see a "blip" of the displayed div.

Sign up to request clarification or add additional context in comments.

Comments

1

Use This Code your issue is resolved.

function myFunction() {
  var x = document.getElementById("myDIV");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}
#myDIV {
  width: 100%;
  padding: 50px 0;
  text-align: center;
  background-color: lightblue;
  margin-top: 20px;
}
<button onclick="myFunction()">Try it</button>

<div id="myDIV">
This is my DIV element.
</div>

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.