Im trying to display the sidebar after clicking the button in the navbar. I have made the JS function, but after clicking the navbar button nothing displays, please help.
Here is my html and css code snippet, please suggest me how can this be done and after opening the sidebar after clicking, i also want a button to appear at same place to close the sidebar.
I am not able to figure out any css code for doing the same.
`
<head>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css" crossorigin="anonymous" />
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<style type="text/css" media="all">
.navbar > .links-sidebar {
display: none;
}
.navbar {
display: flex;
background: #000000;
padding: 25px;
justify-content: space-between;
}
.navbar > a > img {
width: 300px;
}
.navbar > .links-sidebar > a {
color: #ffffff;
font-size: 16px;
text-decoration: 1.2px underline #ff8c00;
}
.navbar > .links-sidebar > a:hover {
text-decoration-thickness: 3px;
}
</style>
</head>
<body>
<div class="navbar">
<a href="#logo"><img src="https://i.ibb.co/3m7Xr45/event-apart-removebg-preview.png" width="100"></a>
<button class="side-btn-open" type="button" onclick="btn_open()"><i class="fas"></i></button>
<div class="links-sidebar">
<a href="#speakers">Speakers</a>
<a href="#findanevent">Find an Event</a>
<a href="#whyattend">Why Attend?</a>
<a href="#registration">Registration Info</a>
<a href="#registernow">Register Now!</a>
<a href="#news">News</a>
</div>
</div>
<script type="text/javascript" charset="utf-8">
function btn_open() {
document.getElementsByClassName("links-sidebar").style.width = "100%";
document.getElementsByClassName("links-sidebar").style.display = "flex";
}
</script>
</body>
`
Here is the output of my code, the navbar button to the right.
2
Answers
getElementsByClassName
returns an array of elements.https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
If you only have one or want to select the first, simply add
[0]
in front of it.(It’s just a simple javascript error, that could’ve been fixed by looking at your browser console. )
Sample:
The issue is with your
getElementsByClassName
function which returns an array-like objects and you need to use it in arraylike fashion.Also, I’ve set up
display:block
instead offlex
to make the sidebar visible.For your query of how to add a close button; one way is you can create a new button in the
HTML
and use the samebtn_open
function to toggle the display of the sidebar. You can obviously play around it to suit your needs.Here is the implementation of the above points: