Skip to content

Instantly share code, notes, and snippets.

@clarkdave
Created May 12, 2013 13:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save clarkdave/5563555 to your computer and use it in GitHub Desktop.
Save clarkdave/5563555 to your computer and use it in GitHub Desktop.
Toggle a popup menu and close it when clicking outside (example using Backbone)
toggleUserMenu: (e) ->
e.preventDefault() if e
container = @$('.user')
# remove body listener if present
$('body').off 'click.menu'
$('.menu', container).toggleClass('visible')
container.toggleClass('open')
if container.hasClass('open')
# add listener to body to close menu if clicked outside it, but wait a moment or else it
# will trigger immediately and hide the menu
setTimeout ( =>
$('body').on 'click.menu', (e) =>
unless $(e.currentTarget).closest(container).length > 0
@toggleUserMenu()
), 200
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment