Using $('#page').click(handler2);
and setting e.stopPropagation();
on the event for #menubutton. This will stop the #page event from triggering if you click on the link.
Adding another clickable element to existing toggle
Question
Currently, clicking #menubutton toggles between these two functions (it slides a menu in and out). How can I close this menu by not only clicking #menubutton again but also by clicking anywhere on #page?
Fiddle: http://jsfiddle.net/3Dwjd/
$(function(){
$('#menubutton').click(function(e){
e.preventDefault();
});
function handler1(){
$("#menubutton").css("color","red");
$("#menu").animate({left:"0"},150);
$("#page").animate({left:"300px"},150);
$("#menubutton").one("click",handler2);
}
function handler2(){
$("#menubutton").css("color","blue");
$("#menu").animate({left:"-300px"},150);
$("#page").animate({left:"0"},150);
$("#menubutton").one("click",handler1);
}
$("#menubutton").one("click", handler1);
});
Solution
OTHER TIPS
You can use css class to indicate open menu
element:
$(function(){
$(document).on('click', '#page.open', handler2);
$('#menubutton').click(function(e){
e.preventDefault();
var $page = $("#page");
if ($page.hasClass('open')) {
handler2();
} else {
handler1();
}
return false;
});
function handler1(){
$("#menubutton").css("color","red");
$("#menu").animate({left:"0"},150);
$("#page").animate({left:"300px"},150).addClass('open');
}
function handler2(){
$("#menubutton").css("color","blue");
$("#menu").animate({left:"-300px"},150);
$("#page").animate({left:"0"},150).removeClass('open');
}
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow