Skip to content

Instantly share code, notes, and snippets.

@AMHOL
Created November 8, 2012 15:09
Show Gist options
  • Save AMHOL/4039356 to your computer and use it in GitHub Desktop.
Save AMHOL/4039356 to your computer and use it in GitHub Desktop.
Create recursive category drop-down navigation by assigning data('children') to navigation li and calling elem.createDropdownFromChildren
(($) ->
$.fn.createDropdownFromChildren = ($level) ->
$elem = $(@)
# if element has children data
unless @data("children") is "undefined"
@bind
# MOUSE ENTER
mouseenter: ->
clearTimeout $(document).data("dd-timeout")
# ul container
$left = (if (typeof $level is "undefined") then $(@).offset().left + $(@).width() else $(@).offset().left)
$top = (if (typeof $level is "undefined") then $(@).offset().top else $(@).offset().top + $(@).height())
$ul = $("<ul />").css(
left: $left
top: $top
position: "absolute"
).addClass("dynamic-dd").attr("belongs-to", $(@).data("identifier")).attr("parent", this).bind(
# MOUSE ENTER
mouseenter: ->
clearTimeout $(document).data("dd-dependent-timeout") if +$(@).attr("belongs-to") is +$(document).data("dd-elem-last")
clearTimeout $(document).data("dd-timeout")
# MOUSE LEAVE
mouseleave: ->
clearTimeout $(document).data("dd-timeout")
$(document).data "dd-timeout", setTimeout(->
$(".dynamic-dd").children().each ->
$(@).unbind()
$(".dynamic-dd").slideUp "fast", ->
$(@).remove()
, 300)
)
$(window).blur ->
$(".dynamic-dd").remove()
# create navigation list
$.each $(@).data("children"), ->
$ul.append $("<li><a href=\"#\">" + @name + "</a></li>").data("children", @children).data("identifier", $.random()).createDropdownFromChildren()
$("body").append $ul
# MOUSE LEAVE
mouseleave: ->
$(document).data "dd-elem-last", @data("identifier")
clearTimeout $(document).data("dd-timeout")
# remove drop-down
$(document).data "dd-timeout", setTimeout(->
$(".dynamic-dd").children().each ->
$(@).unbind()
$(".dynamic-dd").slideUp "fast", ->
$(@).remove()
, 300)
clearTimeout $(document).data("dd-dependent-timeout")
$(document).data "dd-dependent-timeout", setTimeout(->
$(".dynamic-dd[belongs-to=\"" + $elem.data("identifier") + "\"]").remove()
, 10)
) jQuery
(($) ->
$.random = ->
+new Date() + Math.floor(Math.random() * 1000000)
) jQuery
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment