jQuery hide element on event outside of element
I've been working on a very simple Jquery script that displays a few mini-dashboards (divs) for users. When someone clicks a link the correct panel is displayed. Very much like Twitter's login panel.
My only problem is that when I click outside the panel it closes as expected but when I click inside the panel it still closes anyway.
There are other html elements inside each panel and I'm wondering if they're "getting in the way" of the main panel div?
account-menu.js
(function($){
$.fn.renderDash = function(openDash, fn) {
var container = $(this);
container.removeClass('no-js');
container.bind('click', function(event){event.preventDefault();clickStart();})
.bind('mouseup', function(event){mouseupDash();})
$(document.body).bind('mouseup', function(event){ // <-- the offending code
if ($(openDash).has(this).length == 0) {
$(openDash).hide();
}
})
function clickStart() {$(openDash).toggle();}
function mouseupDash() {return false;}
};
})(jQuery);
index.html
...
<script src="jquery-1.4.4.min.js" type="text/javascript"></开发者_运维知识库script>
<script src="account-menu.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.panel1-start').renderDash("#panel1");
$('.panel2-start').renderDash("#panel2");
$('.panel3-start').renderDash("#panel3");
});
</script>
...
</head>
<body>
...
<ul>
<li>
<a href="" class="panel1-start">Panel 1 Link</a>
<ul id="panel1">
<li>Panel 1 Content</li>
</ul>
</li>
panel2, panel3, etc...
Update: I just added a snippet of the html code. Might make things a bit clearer.
Have you tried using this;
container.bind('click', function(event){event.preventDefault();clickStart();})
.bind('mouseup', function(event){event.stopPropagation();mouseupDash();})
It should stop the mouseup event travelling to the document body.
EDIT
Made an example from the now supplied code. It is dirty but should give you a starting point. The .stopPropagation()
was correct but it was being applied to the wrong element. The panels are shown on first load and clicking them will hide them all. However once you toggle them the .stopPropagation()
will be invoked and it all should work. Only testde in Chrome.
Call event.stopPropagation();
in the click handler of your inner element. This prevents the outer elements from receiving the click event. Same applies for your other mouse events of course.
精彩评论