Created
July 10, 2014 12:17
-
-
Save timruffles/a4b6a928df8a961a6fb6 to your computer and use it in GitHub Desktop.
small tooltip
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Tooltip = ({@overEl,content,event,tooltipClass,clickable}) -> | |
@cleanup = [] | |
@el = $("<div class=tooltip></div>") | |
@el.addClass tooltipClass if tooltipClass | |
@el.append content | |
@el.css "visibility": "hidden" | |
$(".wrap").append @el[0] | |
@rect = @el[0].getBoundingClientRect() | |
@updateDimensions() | |
@keepPositioned = @keepPositioned.bind(this) | |
@keepPositioned(event) | |
unless clickable | |
document.body.addEventListener "mousemove", @keepPositioned | |
@cleanup.push => | |
document.body.removeEventListener "mousemove", @keepPositioned | |
out = (event) => | |
return if event.target == @el || event.target == @overEl | |
@remove() | |
$(document.body).off "mouseover", out | |
$(document.body).on "mouseover", out | |
@show() | |
return | |
Tooltip.listeners = -> | |
$(document.body).on "mouseover", (event) -> | |
if event.target.classList.contains "has_tooltip" | |
klass = $(event.target).attr("tooltip-class") | |
tooltipClass = klass || false | |
new Tooltip({tooltipClass, event: event, overEl: event.target, content: $(event.target).attr("data-content")}) | |
Tooltip.prototype = | |
px: (x) -> "#{Math.round x, 1}px" | |
nudge: 15 | |
clientPadding: 5 | |
remove: -> | |
@cleanup.forEach (fn) -> fn() | |
@cleanup = [] | |
@el.remove() | |
@el = false | |
@overEl = false | |
keepPositioned: -> | |
top = @overRect.top + @overRect.height + @nudge + window.scrollY | |
if top > @maxY | |
top = Math.max(@overRect.top - @rect.height - @nudge - 5 + window.scrollY,0) | |
left = Math.max(@overRect.left + @overRect.width / 2 - @rect.width / 2 + window.scrollX,0) | |
if left > @maxX | |
left = @maxX | |
@el.css top: top, left: left | |
show: -> | |
@el.css visibility: "visible" | |
documentResized: -> | |
@updateDimensions() | |
updateDimensions: -> | |
@overRect = @overEl.getBoundingClientRect() | |
{@clientHeight,@clientWidth} = document.body | |
@maxX = @clientWidth - @rect.width - @clientPadding + window.scrollX | |
@maxY = @clientHeight - @rect.height - @clientPadding + window.scrollY | |
Tooltip.listeners() | |
window.Tooltip = Tooltip |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment