Responsive navigation with jQuery

In the past posts, we see that our navigation is taking the entire viewing space. To optimize the navigation we can take help of jQuery’s hide() and show() functions. Check the Demo here with the explanation given below.

$(document).ready(function(){
if($(‘.navigationWrap’).width()<480)
{
$(‘.navigationWrap’).hide();
$(‘.menuBtn’).css(‘display’,’block’);
} else
{
$(‘.navigationWrap’).show();
}
$(window).resize(function(e) {
if($(‘.navigationWrap’).width()<480)
{
$(‘.navigationWrap’).hide();
$(‘.menuBtn’).css(‘display’,’block’);
}
else
{

$(‘.menuBtn’).hide();
$(‘.navigationWrap’).show();
}
});
$(‘.menuBtn’).click(function(e) {
$(‘.navigationWrap’).slideToggle();
});
});

On loading the document, we are checking if the size of the navigation wrapper is less than 480px i.e. if the screen size of the device in which the document is currently being viewed is less than 480px. If it is true then we are hiding the navigation and showing an anchor as a Menu button which will act as a toggle button.

I have written one more event handler function for window re-size. I have used the same logic for this block also that is used in the onReady. In the end I have applied a slideToggle function to the navigation Wrapper on click() event for the menu button. With this code we have optimized the screen for small devices.

About the Author

Pravin Varma

Tech Lead at Calsoft

You may also like these