Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
App.Lib.GlobalEvents =
###
This will trigger the callback whenever the user clicks on something outside
the given element. If the user clicks on something insied `el`, it will not
trigger the callback.
You can give it many elements using jQuery's `#add`:
$els = $('.my-element').add($('.some-other-element'))
App.Lib.GlobalEvents.onClickedOutside $els, =>
# do something
###
onClickedOutside: (el, callback) ->
$el = $(el)
# This get's executed when leaving the page using Turbolinks. In that case,
# the whole body get's erased, together with our bindings, but in this case,
# `document` stays the same so we have to manually clear the bindings.
$(document).on 'turbolinks:before-cache', ->
$(document).unbind '.app-global-event'
$(document).on 'mouseup.app-global-event', (e) =>
return if $el.is(e.target) or $el.has(e.target).length isnt 0
callback()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment