Good evening,
I am having trouble trying to work out why I have to click the test button twice to activate the jquery function where a side navigation bar will slide in from the left. I wanted to do this by targeting the width css class to make it 'grow'.
Then when I click the close button it returns to normal.
Here is the code shown below I hope there is enough there to go on forgive me I am fairly new to this:
HTML:
<a href="" class="test">Click me</a>
<div class="sidenav">
<div class="closebtn"><a href="">Close me</a></div>
</div>
.sidenav {
padding-top: 50px;
height: 100vh;
width: 0;
position: fixed;
z-index: 1;
top: 0;
left: 0;
background-color: #111;
overflow-x: hidden;
transition: 0.5s;
color: #ee81e0;
}
.test {
padding: 10px 20px;
border: 1px solid #d4127e;
}
$(document).ready(function(){
$(".test").click(function(){
$(".sidenav").css('width', '350px');
});
});
$(document).ready(function(){
$(".closebtn").click(function(){
$(".sidenav").css('width', '0px');
});
});
You need to disable the default behavior of the a
tag if you want to stay on the same page and just toggle the nav. By default, the browser will try to follow the a
tag when you click on it. Since your href
attribute is empty, that will just try to go to the current page, or effectively reload the page. You can keep the browser from trying to follow the link by passing the e
event to your click handler function, and calling e.preventDefault()
$(document).ready(function() {
$(".test").click(function(e) {
$(".sidenav").css('width', '350px');
e.preventDefault();
});
});
$(document).ready(function() {
$(".closebtn").click(function() {
$(".sidenav").css('width', '0px');
});
});
.sidenav {
padding-top: 50px;
height: 100vh;
width: 0;
position: fixed;
z-index: 1;
top: 0;
left: 0;
background-color: #111;
overflow-x: hidden;
transition: 0.5s;
color: #ee81e0;
}
.test {
padding: 10px 20px;
border: 1px solid #d4127e;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="" class="test">Click me</a>
<div class="sidenav">
<div class="closebtn"><a href="">Close me</a></div>
</div>