Skip to content

Instantly share code, notes, and snippets.

@PikachuEXE
Created April 26, 2013 05:13
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 PikachuEXE/5465161 to your computer and use it in GitHub Desktop.
Save PikachuEXE/5465161 to your computer and use it in GitHub Desktop.
Toggle Display A small JavaScript to toggle display of target element(s)
###
Toggle Display
Put the data attributes on a button or link
Required attributes:
data-toggle: 'display'
data-target: selector of target element
Optional attibutes:
data-effect: 'slide', 'fade', other values (no effect)
data-hide: presence of this attribute will cause target element to be hidden on start
###
jQuery ($) ->
selector = '[data-toggle="display"][data-target]'
# === Hide toggle target on start or after AJAX ===
hideTargetOnStart = ->
$this = $(this)
$target = $($this.data('target'))
# Use this class name as a flag of processed
unless $this.hasClass('js-toggle-display-init-done')
$this.addClass('js-toggle-display-init-done')
if $this.data('hide')?
$target.hide()
# On document ready
$toggleButtons = $(selector)
$toggleButtons.each(hideTargetOnStart)
# On AJAX success
$(document).ajaxSuccess ->
$toggleButtonsAfterAjax = $(selector)
$toggleButtonsAfterAjax.each(hideTargetOnStart)
# === Hide toggle target on start or after AJAX ===
# === Toggle target on click ===
# Delegated event for click
$(document).on "click", selector, ->
$this = $(this)
$target = $($this.data('target'))
if $this.data('effect') == 'slide'
$target.slideToggle()
else if $this.data('effect') == 'fade'
$target.fadeToggle()
else
$target.toggle()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment