Skip to content

Instantly share code, notes, and snippets.

@gosukiwi
Created September 26, 2019 17:26
Show Gist options
  • Save gosukiwi/0f89d9e54bb98c3e6f72de255d806f65 to your computer and use it in GitHub Desktop.
Save gosukiwi/0f89d9e54bb98c3e6f72de255d806f65 to your computer and use it in GitHub Desktop.
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