javascript - JQuery - also trigger change on click away - Stack Overflow

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

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 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!

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 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!

Share Improve this question asked May 23, 2011 at 12:13 JamisonJamison 2,3484 gold badges27 silver badges31 bronze badges 1
  • Bind a click handler to the document or body element. – Felix Kling Commented May 23, 2011 at 12:16
Add a ment  | 

2 Answers 2

Reset to default 5

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>

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745674567a4639609.html

相关推荐

  • javascript - JQuery - also trigger change on click away - Stack Overflow

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

    5小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信