Add A Slideout Sidebar To A Responsive Theme

Josh Pollock - August 20, 2013

Gmail Mobile MenuGmail Mobile Menu

Note: this is an updated version of my original post, with new and improved code and links to more examples.

On any screen, not just the small-screen, getting your content front and center is important. One way to accomplish this is to do away with the once ubiquitous sidebar. Facebook, and other mobile apps have set a standard for hidden menus that slide out of the side of the page when you click the three lines menu icon. Browsing on mobile devices is now three times more common than it was two years ago, which highlights the importance of making your website’s layout mobile-friendly.

Last year’s WordPress default theme Twenty Thirteen is one example of life after the sidebar. On one hand, I am all for getting rid of sidebars, as they take up valuable screen space for content I don’t need most for most of the time I am viewing a page. On the other hand, sidebars are generally full of important links to other content when I need it. This is why I’m less a fan of getting rid of the sidebar all together, but often like to hide it until the user needs it.

Browsing on mobile devices is now three times more common than it was two years ago, which highlights the importance of making your website’s layout mobile-friendly. On any screen, not just the small-screen, getting your content front and center is important.

My Experience With Slide-Out Sidebars

I have actually developed three different themes with slide-out sidebars at this point, each with a different method for hiding and showing the sidebar. In my theme _Second Foundation, which this site is running a child theme of, I used Foundation’s OffCanvas component for the slide-out sidebar. I also wrote a child theme for Twenty Fourteen (download link,) along with Chris Knowles for a post on WPMUDEV, that uses the jQuery plugin Sidr. I also have my own Twenty Fourteen child theme, called The Falcon, for which I wrote my own jQuery for the mobile sidebar, using Sidr‘s CSS.

Each of these options has its advantages and disadvantages. Sidr and OffCanvas are widely used open source software so you are benefiting from the real world testing of everyone who has every used it. Still, my favorite is my own code from The Falcon. It’s super-light weight at less than half a kilobyte minimized. Sure Sidr, minimizes to 3k, but mine is 100 times smaller and every byte matters on slow mobile devices/ networks.

Also, simple means it’s easy to modify. That’s especially true when you have a tutorial that walks you through how it was built:)

How I Built My Mobile Slide-Out Sidebar

Preparing The Sidebar

If you take a look at the sidebar.php file in my theme you will see that a totally different sidebar is being included based on if a mobile device is being used to load the page, using wp_is_mobile() to load the alternate code on mobile devices only. This allows me to include a different widget area, and mobile sidebar menu area. If you want to learn more about how this was built, see the section in the WPMUDEV article, as it is basically the same code in that article as in my theme.

The key points are to add the id of “mobile-sidebar” and the classes “sidr hide” to the container containing the mobile sidebar. This is not a necessary step if you want to use the same widget area and mobile, you can skip it. Just make sure to follow the optional step below when I discuss the JavaScript for this.

If you do go with the separate mobile widget area and menu, be sure to register them before going any further. Feel free to borrow from my theme for that.

Adding A Toggle

You will also need to make sure that your theme has a toggle for expanding the menu. I do it using the three lines Genericon that has become the standard for menu. If you’re theme doesn’t already have Genericons, be sure to add them to your theme or enable the plugin Genericon’d.

In the appropriate place in your header, add code, like the example below to show the toggle, when on a mobile device. Be sure, if you change the ID of the link to adjust that in the JavaScript as well.

<?php
if ( wp_is_mobile() ) : ?>
<a id="menu-toggle" class="second" title="<?php _e( 'Click To Show Sidebar', 'yt1300' ); ?>" href="#"><span class="genericon genericon-menu"></span></a>
<?php
endif;
view raw 1-slideout.php hosted with ❤ by GitHub

 

Enqueuing the Resources

The next thing to do is to add the JavaScript and CSS to your theme. Create a new file in your theme’s js directory called ‘slideout.js’ and also add one of Sidr’s CSS files, either the dark theme or the light theme to your theme’s css directory. Then in your functions.php, add this function and action to load these new resources:

<?php
function slug_slideout() {
//add css and js
wp_enqueue_script( 'slideout-sidebar', get_stylesheet_directory_uri().'/slideout.js', array('jquery'), null, true );
//Be sure to set the right theme (dark or light here)
wp_enqueue_style( 'sidr', get_stylesheet_directory_uri().'/css/jquery.sidr.dark.css');
}
add_action( 'wp_enqueue_scripts', 'slug_slideout' );
view raw 2-slideout.php hosted with ❤ by GitHub

Additional CSS

The script I will be showing you in the next section relies on two classes “hide” and “unhide” which simply set the display property of the sidebar. The hide class starts off being redundant, as the class sidr also hides the sidebar, but it is helpful as we will need it to hide the sidebar after revealing it. It is necessary to have it there from the beggining as the JavaScript will check for its presence. You can add the two classes, shown below, to your theme’s style.css:

.hide {
display: none;
}
.unhide {
display: inline;
}
view raw 3-slideout.css hosted with ❤ by GitHub

The Javascript Itself

Now time to make the magic happen. The JavaScript I wrote is actually pretty simple. Just 28 lines unminimized. It does three things:

  1. Adds margin-left to the sidebar equal to it’s width on page load. When shown, it animates resetting that value to zero and does the reverse when hiding. This creates the slide in and slide out effect.
  2. Animates the opacity of the sidebar as it slides.
  3. Hide and unhide the sidebar to add or remove it from the document flow.

I will now walk you through how I accomplished each of these steps with very simple jQuery. But before beginning take a look at the first few lines:

jQuery(document).ready(function($) {
//put IDs for sidebar and toggle in vars
var toggle = "#menu-toggle";
var slideout = "#secondary-mobile";
view raw 4-slideout.js hosted with ❤ by GitHub

Besides creating the jQuery noConflict wrapper, this puts the id of the toggle for the sidebar and the sidebar itself into the variables ‘toggle’ and ‘slideout’ respectively. These variables are used in a few places in the code and create one place for updating the container IDs if they ever change. If you are using different container IDs then I am for your toggle or mobile sidebar, be sure to change them here.

The next part of the code calculates the width of the sidebar and then sets that value as for the margin-left property on the sidebar. This is accomplished by measuring the width of the sidebar with jQuery’s width() function and converting it to a negative number, like this:

//calculate the width of the mobile sidebar and put inverse in var
var slideoff = -Math.abs( $( slideout ).width() );
//add margin-left to mobile sidebar to push off canvas
$( slideout).css( "marginLeft", slideoff );
view raw 5-slideout.js hosted with ❤ by GitHub

Note that the width will calculate once and will not adjust if the window is resized, which is not much of an issue with mobile devices, but can be an issue if the orientation changes. Right now I don’t address this but probably will in the future, probably by converting these lines into a function and referring it when an orientation change is detected, but that is a tricky thing to pull of with maximum device support. That’s a subject for a future tutorial.

Now it is time to do the actual showing and hiding off the sidebar. Here is the skeleton of the code that makes this happen:

$( toggle ).on('click', function () {
if ( $( slideout ).hasClass( 'hide' )) {
//do stuff to show sidebar
} else {
//do stuff to hide sidebar
}
}); //end slideout function
view raw 6-slideout.js hosted with ❤ by GitHub

Taking a look at this without any action inside of it is helpful as it shows the mechanism of checking if the sidebar has the class ‘hide’ or not when ever the toggle link is clicked on. This is how the script determines if the sidebar is currently hidden, and therefore needs to be shown, or if its currently being shown and needs to be hidden. You can also use this as to build your own hide/ show functions if you have a method that works better for your site.

The first thing that is done is remove the hide class and add the unhide class, or vise versa. Once there we animate the margin-left and opacity either up to opacity 1 and margin-left 0 or down to opacity 0 and a value of margin-left equal to the value ‘slideoff’, which is the width of the sidebar that we calculated earlier. Note that the class changes precede the animation when showing and follow it, as a callback for the animation when hiding. Also, I left a place for adding a callback after showing the animation that you can add your own callback if needed.

Here is the complete code for the script, with our animations:

jQuery(document).ready(function($) {
//put IDs for sidebar and toggle in vars
var toggle = "#menu-toggle";
var slideout = "#secondary-mobile";
//calculate the width of the mobile sidebar and put inverse in var
var slideoff = -Math.abs( $( slideout ).width() );
//add margin-left to mobile sidebar to push off canvas
$( slideout).css( "marginLeft", slideoff );
//When toggle is clicked show the slideout
$( toggle ).on('click', function () {
if ( $( slideout ).hasClass( 'hide' )) {
$( slideout ).removeClass( 'hide').addClass( 'unhide' ).animate({
opacity: 1,
marginLeft: 0,
}, 500, function() {
//I can haz callback?
});
} else {
$( slideout ).animate({
opacity: 0,
marginLeft: slideoff,
}, 500, function() {
$( slideout ).addClass( 'hide').removeClass( 'unhide' );
});
}
}); //end slideout function
}); //end noConflict
view raw 7-slideout.js hosted with ❤ by GitHub

As you can see at the end of the animate() functions these animations are set to last 500 milliseconds. You can adjust that time as you see fit.

Optional Step

If you do not have a separate mobile sidebar that’s fine, you just need to add two classes to your sidebar itself, but only on mobile. You will need to adjust the value of the variable slideout to match the id of your main sidebar.

Adding the additional classes on mobile to the outermost container of your sidebar can be done on the second line of the JavaScript, since this script is only loaded on mobile. Simply add this right after the jQuery conCoflict wrapper on line one:

$( slideout ).addClass( 'sidr hide' );

Wrap-Up And Slide Out

That’s about it. Want to see a demo? Then preview my theme The Falcon from a mobile device.

Of course this is just a simple, yet totally functional example. You can and should customize it to fit your needs. Some other things you may want to experiment with are: switching sides of the page, having the sidebar slide out of the top of the page, and populating the sidebar with a menu instead of widget areas. You might also want to wrap the php functions in wp_is_mobile so the sidebar only hides for mobile devices. I’d love to see what you make with this and any cool twists you come up with. Please share your creations in the comments or on Twitter.