fevangelou
7/3/2013 - 7:05 AM

A lightweight javascript tooltip

A lightweight javascript tooltip

//
// ToolTip
//
// source: http://sixrevisions.com/tutorials/javascript_tutorial/create_lightweight_javascript_tooltip/

var tooltip = function () {
  var id = 'tt';
	var top = 3;
	var left = 3;
	var maxw = 300;
	var speed = 10;
	var timer_show = 100, timer_hide = 5;
	var endalpha = 95;
	var alpha = 0;
	var tt,t,c,b,h,d;
	var ie = document.all ? true : false;
	return{
		show:function(v,w){
			if(tt == null){
				tt = document.createElement('div');
				tt.setAttribute('id',id);
				t = document.createElement('div');
				t.setAttribute('id',id + 'top');
				d = document.createElement('div');
				d.setAttribute('id',id + 'chk');
				c = document.createElement('div');
				c.setAttribute('id',id + 'cont');
				b = document.createElement('div');
				b.setAttribute('id',id + 'bot');
				tt.appendChild(t);
				tt.appendChild(d);
				tt.appendChild(c);
				tt.appendChild(b);
				document.body.appendChild(tt);
				tt.style.opacity = 0;
				tt.style.filter = 'alpha(opacity=0)';
				document.onmousemove = this.pos;
			}
			tt.style.display = 'block';
			c.innerHTML = v;
			d.innerHTML = v;
			tt.style.width = d.offsetWidth;
			//tt.style.width = w ? w + 'px' : 'auto';
			if(!w && ie){
				t.style.display = 'none';
				b.style.display = 'none';
				tt.style.width = tt.offsetWidth;
				t.style.display = 'block';
				b.style.display = 'block';
			}
			if(tt.offsetWidth > maxw){tt.style.width = maxw + 'px'}
			h = parseInt(tt.offsetHeight) + top;
			clearInterval(tt.timer);
			tt.timer = setInterval(function(){tooltip.fade(1)},timer_show);
		},
		pos:function(event){
			var u = ie ? event.clientY + document.documentElement.scrollTop : event.pageY;
			var l = ie ? event.clientX + document.documentElement.scrollLeft : event.pageX;
			tt.style.top = (u - h) + 'px';
			tt.style.left = (l + left) + 'px';
		},
		fade:function(d){
			var a = alpha;
			if((a != endalpha && d == 1) || (a != 0 && d == -1)){
				var i = speed;
				if(endalpha - a < speed && d == 1){
					i = endalpha - a;
				}else if(alpha < speed && d == -1){
					i = a;
				}
				alpha = a + (i * d);
				tt.style.opacity = alpha * .01;
				tt.style.filter = 'alpha(opacity=' + alpha + ')';
			}else{
				clearInterval(tt.timer);
				if(d == -1){tt.style.display = 'none'}
			}
		},
		hide:function(){
			if (tt==null) return;
			clearInterval(tt.timer);
			tt.timer = setInterval(function(){tooltip.fade(-1)},timer_hide);
		}
	};
}();