简体   繁体   中英

Hide toggled div when click outside (Compatible with native jQuery's toggle)

I have elements working with native Jquery's toggle. These elements are toggled using buttons with inline script onclick="$('#elementname').toggle();return false" that toggles each element, all using the same jQuery's Toggle. How can I hide the divs when user click outisde these divs with compatible jQuery's Toggle code?

You can use onblur="toggle(false)" inside your #navmenu, but that will only work if #navmenu is a form element such as input or textarea.

Another way to do it is detect click on the document to hide #navmenu, and prevent click on #navmenu. You also need to prevent propagation of all clicks on #navmenu and the button. Trouble is that the return false in your button onclick does not work, meaning that the document click will fire. You would need to have some logic with flags to prevent that, but it's easier to remove the inline script, which is recommended anyway. Then you get something like:

https://jsfiddle.net/3Luo34m1/

<button></button>
<p id="navmenu">Testing 123</p>

$(document).on("click", function(e) {
  if (e.target.id == 'navmenu') return false; // prevent click on #navmenu
  $('#navmenu').toggle(false); // hide()
});
$('button').on("click", function() {
  $('#navmenu').toggle();
  return false;
});

BTW, if you have multiple buttons and #navmenu's you need to use classes instead of id's.

Try with this:

$(document).click(function(event){
    if(event.target.classList.contains('.target-div') === false){
    $('.target-div').removeClass('remove toggled class');
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM