'튤팁'에 해당되는 글 1건

  1. 2007/08/20 자바스크립트로 구현한 튤팁(Tooltip)

자바스크립트로 구현한 튤팁(Tooltip)

tag속성중에 title 속성을 그대로 javascript로 구현했다. 이유는 title 속성은 레이어가 뜨는데 약간의 델리이 타임이 있다. 그 딜레이 타임을 없애 달라는 요구에서다. 당연히 css나 속성값으로 딜레이타임을 조정할수 없어서 javascript로 구현했다.

/* 튤팁 박스
   by junsung park */
var bTooltip =
{
 tip_id : "btooltip",
 makeLayer : function (str)
 {  
  var tip_obj = document.getElementById(this.tip_id);
  if (tip_obj==undefined)
  {
   var tip = document.createElement("div");
   tip.id = this.tip_id;
   tip.style.backgroundColor= "#FFFFE1";
   tip.style.fontFamily= "돋움";
   tip.style.fontSize= "12px";
   tip.style.padding= "2px";
   tip.style.color= "#000";
   tip.style.border= "1px solid #000";
   tip.style.position= "absolute";
   tip.style.zIndex= "99999";
   tip.style.display= "none";
 
   document.body.appendChild(tip);
   tip.appendChild(document.createTextNode(str));
  }
 },
 moveLayer : function (e)
 {
  var xp = 0, yp = 0;
  if (document.all) 
  {
   xp = event.clientX + document.documentElement.scrollLeft;
   yp = event.clientY + document.documentElement.scrollTop;
  }else
  {
   xp = e.pageX;
   yp = e.pageY;
  }
  xp += 10;
  yp += 10;
  var tip_obj = document.getElementById(this.tip_id);
  if (tip_obj!=undefined)
  {
   tip_obj.style.top = yp + "px";
   tip_obj.style.left = xp + "px";
   tip_obj.style.display= "block";
  }
 },
 hiddenLyaer : function (e)
 {
  var to = e?e.relatedTarget:event.toElement;
  var to_id = null;  
  try
  {
   to_id = to.id;
  }
  catch (e)
  {
   to_id = null;
  }
  if (this.tip_id==to_id)
  return;
  if (document.all)
  {
   try
   {
    document.getElementById(this.tip_id).removeNode(true);
   }
   catch (e){}  
  }else
  {
   try
   {
    document.body.removeChild(document.getElementById(this.tip_id));
   }
   catch (e){}
  }
 },
 on : function (tg)
 {
  var str = tg.title;
  tg.title= "";
  bTooltip.makeLayer(str);
  tg.onmouseover = new Function("bTooltip.makeLayer('" + str + "')");
  tg.onmousemove = new Function("bTooltip.moveLayer(arguments[0])");
  tg.onmouseout = new Function("bTooltip.hiddenLyaer(arguments[0])");
 }
}

아래처럼 최대한 사용하기 편하게 되어 있다. 예외처리도 다 했다. 다만, 튤팁에 들어갈 내용에 따옴표가 들어간다면 서블릿단에서 이미 처리되어 뿌려줘야 겠다. 이부분은 어쩔수 없는 부분 같다.

사용법

<img src="http://cfs.flvs.daum.net/files/15/57/65/50/6122988/thumb.jpg" onmouseover="bTooltip.on(this)", title="어쩌고">
<a href="" onmouseover="bTooltip.on(this)" title="어쩌고">에이링크</a>