0
votes

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?

2
Shouting will get you nowhere. - user1106925
@squint Comming here only for spell it and downvote an important question will get you nowhere. - dani 'SO learn value newbies'
Not true since you fixed the shouting. You don't have any votes on your question though, so not sure what you're referring to. Good luck with your "important" question. - user1106925
The question is not clear. You should specify where you need to click and include the HTML code too. - Fabricio

2 Answers

0
votes

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.

0
votes

Try with this:

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