Skip to content

Instantly share code, notes, and snippets.

@mshwery
Created February 15, 2012 23:11
Show Gist options
  • Save mshwery/1839924 to your computer and use it in GitHub Desktop.
Save mshwery/1839924 to your computer and use it in GitHub Desktop.
Fancybox Replacement
$.betterbox = ($obj, options) ->
defaults = {
'relativeTo' : ''
'boundTo' : ''
'outerBox' : '#outerBox'
'innerBox' : '#innerBox'
'direction' : 's' # n, e, s, w direction
'offsetTop' : 15
'maxWidth' : 420
'minWidth' : 390
'buffer' : 10 # buffer distance between edges of screen and betterbox object
'maxHeight' : ($(window).height() * .75)
}
opt = $.extend(defaults, options)
getNewBox($obj, opt)
getNewBox = ($obj, opt) ->
setupOuterBox(opt)
$(opt.innerBox).empty().append($obj)
repositionBox(opt)
repositionBox = (opt) ->
setWidth(opt)
getOrientation(opt)
setWidth = (opt) ->
$(opt.innerBox).css("width", getWidth(opt.innerBox, opt))
return getPositionLeft(opt)
getWidth = (obj, opt) ->
return Math.max(opt.minWidth, Math.min($(obj).width(), opt.maxWidth))
getPositionLeft = (opt) ->
posLeft = $(opt.relativeTo).offset().left
left = ( posLeft + ( $(opt.relativeTo).outerWidth() / 2 ) ) - ( $(opt.innerBox).outerWidth() / 2 )
right = ( $('body').width() - opt.buffer ) - ( posLeft + $(opt.relativeTo).outerWidth() )
if left < opt.buffer
$(opt.innerBox).css({'left': posLeft}).addClass('west')
else if (left + $(opt.innerBox).outerWidth()) > ($('body').width() - opt.buffer)
$(opt.innerBox).css({'right': right}).addClass('east')
else
$(opt.innerBox).css({'left': left})
getOrientation = (opt) ->
pos = $(opt.relativeTo).offset()
top = pos.top + $(opt.relativeTo).outerHeight() + opt.offsetTop
bottom = -(pos.top - opt.offsetTop)
childHeight = $(opt.innerBox).children().outerHeight()
docHeight = $('body').height()
if ( top ) > (docHeight * .66)
$(opt.innerBox).addClass('north').children().css({'bottom': bottom})
else
$(opt.innerBox).addClass('south').children().css({'top': top})
setupOuterBox = (opt) ->
$(opt.outerBox).remove() # remove old instances of outerbox
outerBox = opt.outerBox.replace('#', '') # strip the pound sign from the string
innerBox = opt.innerBox.replace('#', '') # strip the pound sign from the string
div = '<div id="' + outerBox + '"><div id="' + innerBox + '"></div></div>' # make a div with an ID of outerbox
$('body').prepend(div)
bindSurroundings(opt)
bindSurroundings = (opt) ->
self = this
$("body").unbind("click").click (e) ->
unless ( $(e.target).closest(opt.innerBox).length ) or ( $(e.target).closest(opt.boundTo).length )
closeBox( $(innerBox).parent() )
$(this).unbind "click"
closeBox = (outerBox) ->
$(outerBox).stop(true, false).fadeOut 100, ->
$(this).remove()​​​​
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment