So, I have a slide out div that can be opened and closed on a button. But I want it to close when you click away from it instead. So open on a button, close when a user clicks somewhere else.
How can I achieve that with this code?
$(document).ready(function() {
var slider_width = $('.slider').width();
$('#slider-button').click(function() {
if($(this).css("margin-right") == slider_width+"px" && !$(this).is(':animated')) {
$('.slider,#slider-button').animate({"margin-right": '-='+slider_width});
}
else {
if(!$(this).is(':animated')) {
$('.slider,#slider-button').animate({"margin-right": '+='+slider_width});
}
}
});
});
.slider{
position:fixed;
height:100%;
background:yellow;
width:200px;
right:0px;
margin-right: -200px;
}
#slider-button{
position:fixed;
width:100px;
height:50px;
right:0px;
background: red;
top:300px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="slider"></div>
<button id="slider-button"></button>
Please be as detailed as possible, I'm still learning this and I'm easily confused.
Thank you!