Skip to content

Instantly share code, notes, and snippets.

@SeanRoberts
Last active August 29, 2015 13:58
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 SeanRoberts/9958488 to your computer and use it in GitHub Desktop.
Save SeanRoberts/9958488 to your computer and use it in GitHub Desktop.
# Often you will want to have behaviour where clicking outside of a certain element will close it,
# for example, maybe you have a menu and you want to close it when the user clicks outside of it.
# In that case what you need to do isn't so much capture a click outside of element as it is
# capture a click anywhere and then stop the closure if it's in the menu, I've been doing it like this:
class DumbMenu
constructor: ->
$(document).on('click', @hideMenu)
$('#menu a').on('click', @preventHide)
hideMenu: =>
$('#menu').hide()
preventHide: (e) =>
e.stopPropagation()
# By firing stopPropagation we stop the click from bubbling up to the document and so @hideMenu
# is never called. Unfortunately there's an annoying issue with this. Say that elsewhere you wanted to
# attach other events to the links in the menu:
class CoolFeature
constructor: ->
$(document).on('click', '#menu a', @doACoolThing)
doACoolThing: (e) =>
e.preventDefault();
window.location = 'http://zombo.com'
# We attach the event to the document because we want it to run on any element that matches #menu a, even ones that are
# created dynamically. But it's not working, because our use of e.stopPropagation() means that the document never receives
# the click event.
# So how do we stop the menu from closing without clobbering all other events?
class LessDumbMenu
constructor: ->
$(document).on('click', @hideMenu)
hideMenu: (e) =>
unless $(e.target).is('#menu *, #menu')
$('#menu').hide()
# Rather than preventing event propagation, we can just check what was clicked and only hide the menu if it wasn't
# the menu or a child of the menu.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment