Furkan Ayık Furkan Ayık - 4 months ago 6
HTML Question

Show/Hide button works but just for sec. (javascript-css-html)

I have a button that hides/shows a

div
. In CSS I wrote
display:none;
for this
div
because I don't want it shown when the page is first loaded. My button works with JavaScript func, and this func including
if-else
and changing the div's display.

The problem is that when I use the button my div is showing for 1 second and it disappears again.

I think it is about my CSS style but JavaScript must have changed the display. So I don't know :( Here is my code (I'm not adding my CSS because it just has
display:none;
about that div)

<script type="text/javascript">
function toggle_visibility(id) {
var e = document.getElementById(id);
if (e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
</script>


And here is the HTML

<div class="butondiv">
<button id="btnshow" class="btn" onclick="toggle_visibility('panelid')" runat="server"> Departments </button>
</div>
<div id="panelid" class="panel" style="display:none;">
<ul class="list-group">
<li class="list-group-item"><a>Dep1 </a> <button runat="server" href="#">Delete</button></li>
<li class="list-group-item"><a>Dep2 </a> <button runat="server" href="#">Delete</button></li>
<li class="list-group-item"><a>Dep3 </a> <button runat="server" href="#">Delete</button></li>
</ul>
</div>

Answer

You should prevent the form submission by explicit adding the type of the button or by js.

<div class="butondiv">
    <button type="button" id="btnshow" class="btn" onclick="toggle_visibility('panelid')" runat="server"> Departments </button>
</div>
Comments