Skip to content

Instantly share code, notes, and snippets.

@bmc
Created December 6, 2012 02:25
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bmc/4221350 to your computer and use it in GitHub Desktop.
Save bmc/4221350 to your computer and use it in GitHub Desktop.
jQuery: Create a "hidden" event handler, to trigger when an element is hidden
# Simulate a "hidden" event by overriding jQuery's hide() method.
oldHide = $.fn.hide
$.fn.hide = (speed, callback) ->
# This isn't a real event. Use "triggerHandler", to fire the jQuery handlers, without
# treating it as a real DOM event.
$(this).triggerHandler('hidden')
oldHide.apply(this, arguments)
# Example of using the above. Imagine a sidebar of links. When a link is clicked, an associated element
# (identified by a "data-target" attribute) is shown. All other sidebar elements are to be hidden. When
# a sidebar element is hidden, it should also be cleared of its contents (which, presumably, came from
# some kind of AJAX call or something).
#
# <div id="sidebar">
# <ul>
# <li><a class="sidebar-link" data-target="#profile">Edit your profile</a></li>
# <li><a class="sidebar-link" data-target="#links">Edit your links</a></li>
# ...
# </ul>
# </div>
$(".sidebar-link").each ->
target = $(this).data("target")
$(target).bind("hidden", ->
# This element has just been hidden. Empty its contents.
$(this).find(".content").empty()
)
$(".sidebar-link").click (e) ->
e.preventDefault()
thisTarget = $(this).data("target")
# Hide all the other ones.
$(".sidebar-link").each ->
target = $(this).data("target")
$(target).hide() unless target is thisTarget
# Show this one.
target = $(this).data("target")
$(target).show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment