52

I'm trying to achieve that a div hides if user clicks anywhere except on the element. I've got following code doing toggle() if user clicks on a button. I want the button click to stay plus if the Details element is visible, reacts to other parts of the screen.

$('.nav-toggle').click(function() {
  //get collapse content selector
  var collapse_content_selector = $(this).attr('href');

  //make the collapse content to be shown or hide
  var toggle_switch = $(this);
  $(collapse_content_selector).toggle(function() {
    if ($(this).css('display') == 'none') {
      //change the button label to be 'Show'
      toggle_switch.html('Show Details');
    } else {
      //change the button label to be 'Hide'
      toggle_switch.html('Hide Details');
    }
  });
});
Machavity
  • 30,841
  • 27
  • 92
  • 100
crs1138
  • 926
  • 1
  • 12
  • 23
  • I probably didn't explain myself well. Have a look at this fiddle http://jsfiddle.net/planxdesign/b9mLB/1/ This is the code as I've got it at the moment, I would like to hide the #details-window in case user clicks at the "hide details" or/and anywhere else apart of the navigation arrows. – crs1138 Oct 04 '12 at 13:17

2 Answers2

32

You can resort to the concept of event delegation.

$(function() {
    $(document).on('click', function(e) {
        if (e.target.id === 'div1') {
            alert('Div Clicked !!');
        } else {
            $('#div1').hide();
        }

    })
});​

Check FIDDLE

I did not understand what you meant by integrating with the other part.. This is the basic idea..

Sushanth --
  • 55,259
  • 9
  • 66
  • 105
  • I would like to stick to the toggle for various reasons. Is there any way how to implement the click anywhere apart of the #details-window while using the toggle()? See my fiddle - http://jsfiddle.net/planxdesign/b9mLB/1/ – crs1138 Oct 11 '12 at 17:01
  • This approach would work but you will need to set the click event to off once the div is hidden like so `$(document).off("click")`. – Daniel Barde Jul 17 '14 at 15:20
  • @DanielBarde . Why would you remove the event binding once the div is hidden.. – Sushanth -- Jul 17 '14 at 18:30
  • @Sushanth-- so that if you are doing a drop down or popup, you could click on its trigger again to show the element, else the element will refuse to show because the event for hiding it is still bound to the document, this will stop even the trigger from working. – Daniel Barde Jul 20 '14 at 19:03
4

You can use the jQuery .blur() function to hide a div when user click on other element (like link, boutton, whathever..)

The blur event is fire when an element is loosing the focus (user select another element on the DOM tree)

I don't understand the link with your toggle. If your toggle button manage the DIV, its inside the toggle function that you should place the hide()/show() on the div, in the same time as updating the text of the button.

coolguy
  • 7,866
  • 9
  • 45
  • 71
MatRt
  • 3,494
  • 1
  • 19
  • 14