var stylus = (function(){ function center(selector) { jQuery(function(){ var el = jQuery(selector); function center() { var w = el.outerWidth() , h = el.outerHeight(); el.css({ top: window.innerHeight / 2 - h / 2 , left: window.innerWidth / 2 - w / 2 }); } jQuery(window).resize(center); center(); }); } function tip(selector, pos, color, width, height) { width = parseInt(width, 10); height = parseInt(height, 10); jQuery(function(){ var el = jQuery(selector) , tip = $('') , canvas = tip.get(0) , ctx = canvas.getContext('2d') , w = el.outerWidth() , h = el.outerHeight() , off = el.offset() , top , left; el.append(canvas); canvas.width = width; canvas.height = height; function calc() { ctx.beginPath(); switch (pos) { case 'top': top = -height; left = w / 2 - width / 2; ctx.lineTo(width / 2, 0); ctx.lineTo(width, height); ctx.lineTo(0, height); break; case 'right': top = h / 2 - height / 2; left = w; ctx.lineTo(0, 0); ctx.lineTo(0, height); ctx.lineTo(width, height / 2); break; case 'bottom': top = h; left = w / 2 - width / 2; ctx.lineTo(width / 2, height); ctx.lineTo(0, 0); ctx.lineTo(width, 0); break; case 'left': top = h / 2 - height / 2; left = -width; ctx.lineTo(0, height / 2); ctx.lineTo(width, 0); ctx.lineTo(width, height); break; } } calc(); tip.css({ top: top, left: left }); ctx.fillStyle = color; ctx.fill(); }); } function snapTo(selector, target, pos, pad) { pad = parseInt(pad, 10); jQuery(function(){ var el = jQuery(selector); target = jQuery(target); function snap() { var w = el.outerWidth() , h = el.outerHeight() , tw = target.outerWidth() , th = target.outerHeight() , off = target.offset() , ww = window.innerWidth , wh = window.innerHeight , auto = 'auto' == pos , top , left; if (auto) pos = 'right'; function calc() { switch (pos) { case 'top': top = off.top - h - pad; left = off.left - w / 2 + tw / 2; break; case 'left': top = off.top - h / 2 + th / 2; left = off.left - w - pad; break; case 'bottom': top = off.top + th + pad; left = off.left - w / 2 + tw / 2; break; case 'right': top = off.top - h / 2 + th / 2; left = off.left + tw + pad; break; } } calc(); if (auto) { // right if (left + w > ww) { pos = 'left'; calc(); } } el.css({ top: top, left: left }); } jQuery(window).resize(snap); snap(); }); } return { snapTo: snapTo , tip: tip , center: center } })()