Reputation: 2242
So I have this nice sliding navigation panel that appears when the screen is narrow enough. I'm pretty pleased with it so far, but I would like it to close when the user clicks/taps outside the panel. How would I modify my jQuery script to make that happen? (I am a jQuery novice)
Site: http://www.toprival.com/temp/side_menu/side_menu1.html
jQuery code:
$(document).ready(function() {
$panel = $("#panel");
$tab = $("#tab");
$menu_icon = $("#menu_icon");
$tab.mousedown(function() {
var currentPanelPosition = $panel.css("left");
var newPanelPosition;
if (currentPanelPosition === "0px") {
newPanelPosition = "-200px";
$menu_icon.css("background-position-y", "0px");
} else {
newPanelPosition = "0px";
$menu_icon.css("background-position-y", "-40px");
}
$panel.animate({"left" : newPanelPosition}, 400, "easeOutExpo");
});
});
Upvotes: 1
Views: 356
Reputation: 11451
You could wrap your header and paragraphs in a div and then on click of that div trigger your menu to close.
<div id="wrapper">
<div id="panel">...</div>
<div id="content">
<h1></h1>
<p></p>
</div>
</div>
Then in your javascript you can add:
$('#content').click(function(){
if (currentPanelPosition === "0px") {
$('#tab').trigger('mousedown');
}
});
As a side note you should probably use 'click' rather than 'mousedown'.
Upvotes: 1
Reputation: 594
You can just add a click listener to your wrapper.
$('#wrapper').on('click', function(e){
$('#panel').animate({"left": "-200px"}, 400, "easeOutExpo");
});
The only issue you're going to have though, is that your panel is within that same wrapper div, so even when you click anywhere within the panel itself, the panel will close.
I think it'd be best for you to move the panel div outside of the wrapper, or as 'jdehlin' suggested, place your paragraphs etc. in a separate div, and attach the click listener to that instead.
Upvotes: 0