Responsive Design for JavaScript
by lovromar
HTML
<div id="outer">
<div id="main"></div>
<div id="sidebar"></div>
</div>
CSS
#outer {
width:80%;
overflow:hidden;
margin:0px auto 0px;
}
#main {
width:60%;
height:700px;
background-color:forestgreen;
float:left;
display:inline;
}
#sidebar {
width:40%;
height:700px;
background-color:black;
float:right;
display:inline;
}
JavaScript
// Responsive JavaScript
$(function() {
function showSidebar() {
$('#outer').stop().animate({width:"80%"}, 400, function() {
$('#main', this).stop().animate({width:"60%"}, 400, function() {
$(this).next().slideDown('slow');
});
});
}
// When the window is resized, execute the if-else function
$(window).resize(function() {
var winWidth = $(window).width(); // Get the window width
// If the window size is smaller than 400...
if(winWidth < 400) {
// Do the animation bellow
$('#sidebar').slideUp('slow', function() {
$(this).prev().stop().animate({width:"100%"}, 400, function() {
$(this).parent().stop().animate({width:"100%"}, 400);
});
});
} else {
// If the window size is greater than 400, run the showSidebar() function!
showSidebar();
}
});
});