I have a problem toggling between display: none; & display: block;
Here is the element i want to toggle:
.dd-content #myLinks{
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
padding: 12px 16px;
z-index: 1;
}
JS:
<script>
function myFunction() {
var x = document.getElementsById("myLinks");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
</script>
Calling on that function:
<a href="javascript:void(0);" class="icon" onclick="myFunction()">Link</a>
What happens now is that the element is displayed as a block and the Link won't toggle it back...
What am i doing wrong?
fiddle: https://jsfiddle.net/kx37dcbv/
There are two issues here:
getElementsById, instead, you should be calling getElementById.<section class="p-menu1">
<nav id="navbar" class="navigation" role="navigation">
<input id="toggle1" type="checkbox" />
<label class="hamburger1" for="toggle1">
<div class="top"></div>
<div class="meat"></div>
<div class="bottom"></div>
</label>
<nav class="menu1">
<div class="dd">
<a href="javascript:void(0);" class="icon" onclick="myFunction()">Link</a>
<div class="dd-content">
<p>Hello World!</p>
</div>
</div>
</nav>
</nav>
</section>
When I run the fiddle and click on your 'Link', I get the error "<a class='gotoLine' href='#283:9'>283:9</a> Uncaught TypeError: Cannot read properties of null (reading 'style')". This tells me that your function call to getElementById is unable to find an element with that ID.
You need to add an id="myLinks" to one of your elements in your HTML. You currently have:
.dd-content #myLinks{
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
padding: 12px 16px;
z-index: 1;
}
but this is just defining the styling for those elements, so for your div <div class="dd-content"> you need to change this to <div class="dd-content" id="myLinks"> in order for your function to be able to find the element identified by that ID.