Reputation: 47
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>
Upvotes: 1
Views: 984
Reputation: 486
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>
Upvotes: 1
Reputation: 1577
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.
Upvotes: 2