开发者

JQuery - also trigger change on click away

I have a basic JQuery script that changes a few divs when you click - thus showing them - via toggle.

<script type="text/javascript">
     $('#content_display').click(function() {
         $(this).toggleClass('selected');
         $('#content_display_selector_container').toggle();
     });
</script>

However - to call the even you need to click only on the first main div with the ID of "content_display".

My question is this: how can I hide these changes using JQuery if开发者_JAVA百科 the user also clicks on BODY - i.e. if you click away, the divs go back to their original hidden state?

Thanks for helping a JQuery clutz!


Something like this should work:

$('body').click(function(e) {
    if (!$(e.target).is('#content_display')) {
        $('#content_display').removeClass('selected');
        $('content_display_selector_container').hide();
    }
});


Hey - found a way to do this - does anyone think there's a better way?

Here's the result:

<script type="text/javascript">
   var mousetrap = false;
   $('body').click(function() {
       if (mousetrap == false) {
          $('#content_display').removeClass('selected');
          $('#content_display_selector_container').hide();
        }
   });
   $('#content_display').hover(function() {
         mousetrap = true;
   },function(){
         mousetrap = false;
});
     $('#content_display').click(function() {
           $(this).toggleClass('selected');
           $('#content_display_selector_container').toggle();
     });
</script>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜