Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Easy tooltips for elements.
- #
- # Examples
- # <span data-tooltip="The fuck was that?">The fuck is this?</span>
- #
- # # Init tooltip
- # $ ->
- # $('[data-tooltip]').tooltip()
- class Tooltip
- @el: null
- @tooltip: null
- @open: false
- @closeTimer: null
- @topMargin: null
- constructor: (el)->
- @el = $(el)
- @createTooltip()
- @bindEvents()
- bindEvents: =>
- @el.bind('mouseover', @mouseOver)
- @el.bind('mouseout', @mouseOut)
- mouseOver: =>
- if @open
- clearTimeout(@closeTimer)
- else
- @show()
- tooltipMouseOver: =>
- clearTimeout(@closeTimer)
- mouseOut: =>
- @closeTimer = setTimeout(@hide, 100)
- createTooltip: =>
- el = $('<div></div>')
- .attr('class', 'tooltip')
- .append($('<i>'))
- .append($("<span class='inner'>#{@el.data('tooltip')}</div>"))
- .bind('mouseover', @tooltipMouseOver)
- .bind('mouseout', @mouseOut)
- @tooltip = el
- show: =>
- return if @open
- @open = true
- $('body').append(@tooltip)
- @topMargin = @tooltip.css('margin-top')
- pos = @findPos()
- @tooltip.css('top', "#{pos.top}px")
- .css('left', "#{pos.left}px")
- @tooltip.animate({opacity: 1, 'margin-top': '0px'}, 200)
- hide: =>
- @tooltip.animate { opacity: 0, 'margin-top': @topMargin }, 200, =>
- @tooltip.detach()
- @open = false
- findPos: =>
- # Find position of middle of element
- pos = @el.offset()
- pos.left += @el.width() / 2
- # Adjust position based on size of tooltip
- pos.top -= @tooltip.outerHeight()
- pos.left -= @tooltip.outerWidth() / 2
- pos
- # Create jQuery plugin
- jQuery.fn.extend
- tooltip: ->
- @.each ()->
- new Tooltip(@)
Add Comment
Please, Sign In to add comment