Eddy Eddy - 2 months ago 7
Javascript Question

Toggle div in and out off screen

I am using the code below to toggle a div out of screen partially, and back in screen fully. This code tells how far "sidebar" is to move offscreen. But in my case this functionality has a problem, due to media queries applied to sidebar width. Therefore I need the code not to state how far over sidebar will move, but how much of sidebar will be left onscreen in pixels. The demo here (with the media queries).

$(document).ready(function () {

$("#toggle").click(function () {
if($(this).hasClass('active')){
$(this).removeClass('active');
$("#sidebar").animate({
left: '0%'
});
}else{
$(this).addClass('active');
$("#sidebar").animate({
left: '-55%'
});
}


});
});

Answer

Simple maths:

Say you want the side bar to have 40px left on the screen, and the rest hidden. So you want to move it left by (width - 40). I.e.

 $(document).ready(function () {
        $("#toggle").click(function () {
            if($(this).hasClass('active')){
                $(this).removeClass('active');
                $("#sidebar").animate({
                    left: '0%'
            });
        } else {
            $(this).addClass('active');
            $("#sidebar").animate({
                left: - ($("#sidebar").width() - 40)
            });
        }
    });
});
html, body {
    width:100%;
    height: 100%;
}
#header {
    width: 100%;
    height: 20%;
    float: left;
    border: 1px solid;
}

#sidebar {
    width: 70%;
    height: 80%;
    position: relative;
    border: 1px solid;
}
#toggle {
    width: 10%;
    height: 40%;
    margin-right: 6.5%;
    margin-top: 3.5%;
    float: right;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="sidebar">SIDEBAR<input type="button" value="Toggle" id="toggle"></div>