jQuery: Hide element on click anywhere else apart of the element

JavascriptJquery

Javascript Problem Overview


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');
    }
  });
});

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questioncrs1138View Question on Stackoverflow
Solution 1 - JavascriptSushanth --View Answer on Stackoverflow
Solution 2 - JavascriptMatRtView Answer on Stackoverflow