Search code examples
javascriptjqueryhtmlcssslidetoggle

Sliding Side Nav Bar


I need help with making a vertical nav bar that slides to the right to reveal more content. I'm aiming towards something similar to the blue bar here: http://www.teehanlax.com/labs/. The nav bar slides out (to the right) when the side navigation bar is clicked, and slides back (to the left) when the x button is clicked.

my code is:

<!--Am I implementing the jQuery right?-->
<!DOCTYPE HTML> <html> <head> <title>Nishad</title> 
<link rel="stylesheet" href="style.css"> 
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"> </script> 

$(function() { $('#nav').click(function() 
{ var leftMargin = ($(this).css('margin-left') === '0px') ? '-150px' : '0px'; $(this).animate({ 'margin-left' : leftMargin }, 500); 
}); 
}); ​ 
</head> <body> <div id="wrapper">
<div id="nav"></div> 
<div id="content"></div> 
</div> </body> </html>

Solution

  • If you inspect the element, you can see that the website is making use of a negative value for the navigation's margin-left. When you click the +, they are setting margin-left to 0px.

    You can get the click effect by attaching a click event handler. The sliding effect can be done using jQuery's animate(). Below is an example what I just mentioned.

    $(function() {
    
      $('#nav').click(function() {
      
      var leftMargin = ($(this).css('margin-left') === '0px') ? '-150px' : '0px';
                     
      $(this).animate({ 'margin-left' : leftMargin }, 500);
       
      });
       
    });
        #wrapper {
            white-space: nowrap;
        }
        #nav, #content {
            height: 500px;
            display: inline-block;
        }
        #nav {
            width: 200px;
            margin-left: -150px;
            cursor: pointer;
            background: lightgreen;
        }
        #content {
            width: 500px;
            background: lightblue;
        }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="wrapper">
            <div id="nav"></div><div id="content"></div>
        </div>

    jsFiddle Demo