Home > Uncategorized > Creating a dynamic tooltip with AJAX

Creating a dynamic tooltip with AJAX

The Tooltip is a common graphical user interface element. It is used in conjunction with a cursor, usually a mouse pointer. The User hovers the cursor over an item, without clicking it, and tooltip may appear – a small hoverbox with information about the being hovered over.

Ajax Tool tip : AJAX is the art of exchanging data with a server, and update parts of a web page – without reloading the whole page. By Using the Ajax tool tip we can show the content of the tooltip is retrieved by Ajax from external files.

  • Files to be used in the Ajax Tool tip
    • ajax-tooltip.html = Main HTML file
    • js/ajax-tooltip.js = Main JS file for the script
    • js/ajax.js = Ajax (SACK library)
    • js/ajax-dynamic-content.js = The dynamic content script from this site
    • css/ajax-tooltip.css = CSS for tooltip
    • images/arrow.gif = Arrow used in the tooltip
    • demo-pages = External files loaded by the tooltip

The files used for demo can be downloaded from here http://www.dhtmlgoodies.com/scripts/ajax-tooltip/ajax-tooltip.zip

Configuration : First, you need to include the js files and css files as in the demo (ajax-tooltip.html).

<script type=”text/javascript” src=”newjs/ajax-dynamic-content.js”></script>

<script type=”text/javascript” src=”newjs/ajax.js”></script>

<script type=”text/javascript” src=”newjs/ajax-tooltip.js”>

The tooltip is called by a mouseover event applied to an <A> tag.

Example:

<a href=”#” onmouseover=”ajax_showTooltip(‘demo-pages/ajax-tooltip.html’,this);return false”>Show Me tooltip!</a>

Working Techniques:

Before Proceeding with the files used in tool tips we must know the usage of the files.

Main HTML file

Where we going to show the tooltip

JS Files

Supporting files to Show the Tool Tip. JS files

We need to have the browser compatible with ajax,

We need to cache the contents of the tooltip so that when the hover  on the content will show without much time.

And Also for the creating div element on the hover function, Place them in appropriate places next to <a> tag show the tool tip

CSS File

The layout(size, colors and arrow) is defined in the CSS.

External File of Content

The Result content is Stored in this Page. This Page can be programmed in such a manner to fetch the contents related to the <a> tag which hovers.

MAIN HTML FILE

The main Html file will have the following lines

<link href=”ajaxtooltip.css” rel=”stylesheet” type=”text/css”>

<script type=”text/javascript” src=”newjs/ajax-dynamic-content.js”></script>

<script src=”newjs/ajax.js”></script>

<script src=”newjs/ajax-tooltip.js”>

<a href=”#” onmouseover=”ajax_showTooltip(‘demo-pages/ajax-tooltip.html’,this);return false”>

Show Me tooltip!

</a>

‘demo-pages/ajax-tooltip.html’ is the file which having the contents need to show

in tool tip action. Files may name as ‘search_contentfile.php?Id=<dynamic idno>’ also. It’s the prettiest way to fetch contents and show them in tooltip.

So the html file putting environment for ajax tooltip show.

The file may contain the all the other lines which used to display other contents in the page

When the action of hover occur it function calls and show tooltip with appropriate contents.

JS Files

1.ajax-tooltip.js:

The function that’s called during hover function ShowTooltip is placed in this file

var ajax_tooltipObj = false;

var ajax_tooltipObj_iframe = false;

var ajax_tooltip_MSIE = false;

if(navigator.userAgent.indexOf(‘MSIE’)>=0)ajax_tooltip_MSIE=true;

function ajax_showTooltip(externalFile,inputObj)

{

if(!ajax_tooltipObj)          /* Tooltip div not created yet ? */

{

ajax_tooltipObj = document.createElement(‘DIV’);

ajax_tooltipObj.style.position = ‘absolute';

ajax_tooltipObj.id = ‘ajax_tooltipObj';

document.body.appendChild(ajax_tooltipObj);

var leftDiv = document.createElement(‘DIV’);         /* Create arrow div */

leftDiv.className=’ajax_tooltip_arrow';

leftDiv.id = ‘ajax_tooltip_arrow';

ajax_tooltipObj.appendChild(leftDiv);

var contentDiv = document.createElement(‘DIV’); /* Create tooltip content div */

contentDiv.className = ‘ajax_tooltip_content';

ajax_tooltipObj.appendChild(contentDiv);

contentDiv.id = ‘ajax_tooltip_content';

if(ajax_tooltip_MSIE){     /* Create iframe object for MSIE in order to make the tooltip cover select boxes */

ajax_tooltipObj_iframe = document.createElement(‘<IFRAME frameborder=”0″>’);

ajax_tooltipObj_iframe.style.position = ‘absolute';

ajax_tooltipObj_iframe.border=’0′;

ajax_tooltipObj_iframe.frameborder=0;

ajax_tooltipObj_iframe.style.backgroundColor=’#FFF';

ajax_tooltipObj_iframe.src = ‘about:blank';

contentDiv.appendChild(ajax_tooltipObj_iframe);

ajax_tooltipObj_iframe.style.left = ‘0px';

ajax_tooltipObj_iframe.style.top = ‘0px';

}

}

// Find position of tooltip

ajax_tooltipObj.style.display=’block';

ajax_loadContent(‘ajax_tooltip_content’,externalFile);

if(ajax_tooltip_MSIE){

ajax_tooltipObj_iframe.style.width = ajax_tooltipObj.clientWidth + ‘px';

ajax_tooltipObj_iframe.style.height = ajax_tooltipObj.clientHeight + ‘px';

}

ajax_positionTooltip(inputObj);

}

During the Process, the files check with the other files about the compatibility of browser, and the status about the content.

The Tooltip is div element created on the process of hovering.

The styles are applied in CSS as per purpose.

Another Main thing in the Tool tip is Showing the tool tip in right place

So the tooltip will be more effective.

The function below is used to determine the position of tool tip.

function ajax_positionTooltip(inputObj)

{

var leftPos = (ajaxTooltip_getLeftPos(inputObj) + inputObj.offsetWidth);

var topPos = ajaxTooltip_getTopPos(inputObj);

/*

var rightedge=ajax_tooltip_MSIE? document.body.clientWidth-leftPos : window.innerWidth-leftPos

var bottomedge=ajax_tooltip_MSIE? document.body.clientHeight-topPos : window.innerHeight-topPos

*/

var tooltipWidth = document.getElementById(‘ajax_tooltip_content’).offsetWidth +  document.getElementById(‘ajax_tooltip_arrow’).offsetWidth;

// Dropping this reposition for now because of flickering

//var offset = tooltipWidth – rightedge;

//if(offset>0)leftPos = Math.max(0,leftPos – offset – 5);

ajax_tooltipObj.style.left = leftPos + ‘px';

ajax_tooltipObj.style.top = topPos + ‘px';

}

The functions below are used to find the positions,

function ajaxTooltip_getTopPos(inputObj)

{

var returnValue = inputObj.offsetTop;

while((inputObj = inputObj.offsetParent) != null){

if(inputObj.tagName!=’HTML’)returnValue += inputObj.offsetTop;

}

return returnValue;

}

function ajaxTooltip_getLeftPos(inputObj)

{

var returnValue = inputObj.offsetLeft;

while((inputObj = inputObj.offsetParent) != null){

if(inputObj.tagName!=’HTML’)returnValue += inputObj.offsetLeft;

}

return returnValue;

}

Thus the Tool Tip is Placed in the Right Place.

Also we need a function to not to display them in mouse out.

The function can be written as follows.

function ajax_hideTooltip()

{

ajax_tooltipObj.style.display=’none';

}

2. ajax.js

The Js. Used to fine the browser compatiablity and ajax functional purposes

function sack(file){

this.AjaxFailedAlert = “Your browser does not support the enhanced functionality of this website, and therefore you will have an experience that differs from the intended one.\n”;

this.requestFile = file;

this.method = “POST”;

this.URLString = “”;

this.encodeURIString = true;

this.execute = false;

this.onLoading = function() { };

this.onLoaded = function() { };

this.onInteractive = function() { };

this.onCompletion = function() { };

this.createAJAX = function() {

try {

this.xmlhttp = new ActiveXObject(“Msxml2.XMLHTTP”);

} catch (e) {

try {

this.xmlhttp = new ActiveXObject(“Microsoft.XMLHTTP”);

} catch (err) {

this.xmlhttp = null;

}

}

if(!this.xmlhttp && typeof XMLHttpRequest != “undefined”)

this.xmlhttp = new XMLHttpRequest();

if (!this.xmlhttp){

this.failed = true;

}

};

this.setVar = function(name, value){

if (this.URLString.length < 3){

this.URLString = name + “=” + value;

} else {

this.URLString += “&” + name + “=” + value;

}

}

this.encVar = function(name, value){

var varString = encodeURIComponent(name) + “=” + encodeURIComponent(value);

return varString;

}

this.encodeURLString = function(string){

varArray = string.split(‘&’);

for (i = 0; i < varArray.length; i++){

urlVars = varArray[i].split(‘=’);

if (urlVars[0].indexOf(‘amp;’) != -1){

urlVars[0] = urlVars[0].substring(4);

}

varArray[i] = this.encVar(urlVars[0],urlVars[1]);

}

return varArray.join(‘&’);

}

this.runResponse = function(){

eval(this.response);

}

this.runAJAX = function(urlstring){

this.responseStatus = new Array(2);

if(this.failed && this.AjaxFailedAlert){

alert(this.AjaxFailedAlert);

} else {

if (urlstring){

if (this.URLString.length){

this.URLString = this.URLString + “&” + urlstring;

} else {

this.URLString = urlstring;

}

}

if (this.encodeURIString){

var timeval = new Date().getTime();

this.URLString = this.encodeURLString(this.URLString);

this.setVar(“rndval”, timeval);

}

if (this.element) { this.elementObj = document.getElementById(this.element); }

if (this.xmlhttp) {

var self = this;

if (this.method == “GET”) {

var totalurlstring = this.requestFile + “?” + this.URLString;

this.xmlhttp.open(this.method, totalurlstring, true);

} else {

this.xmlhttp.open(this.method, this.requestFile, true);

}

if (this.method == “POST”){

try {

this.xmlhttp.setRequestHeader(‘Content-Type’,’application/x-www-form-urlencoded’)

} catch (e) {}

}

this.xmlhttp.send(this.URLString);

this.xmlhttp.onreadystatechange = function() {

switch (self.xmlhttp.readyState){

case 1:

self.onLoading();

break;

case 2:

self.onLoaded();

break;

case 3:

self.onInteractive();

break;

case 4:

self.response = self.xmlhttp.responseText;

self.responseXML = self.xmlhttp.responseXML;

self.responseStatus[0] = self.xmlhttp.status;

self.responseStatus[1] = self.xmlhttp.statusText;

self.onCompletion();

if(self.execute){ self.runResponse(); }

if (self.elementObj) {

var elemNodeName = self.elementObj.nodeName;

elemNodeName.toLowerCase();

if (elemNodeName == “input” || elemNodeName == “select” || elemNodeName == “option” || elemNodeName == “textarea”){

self.elementObj.value = self.response;

} else {

self.elementObj.innerHTML = self.response;

}

}

self.URLString = “”;

break;

}

};

}

}

};

this.createAJAX();

}

3.ajax-tooltip.js

This Js function used to get the details from external file and used to store the details in cache so that visited contents can display with less time consuming

function ajax_showContent(divId,ajaxIndex,url)

{

document.getElementById(divId).innerHTML = dynamicContent_ajaxObjects[ajaxIndex].response;

if(enableCache){

jsCache[url] =    dynamicContent_ajaxObjects[ajaxIndex].response;

}

dynamicContent_ajaxObjects[ajaxIndex] = false;

}

function ajax_loadContent(divId,url)

{

if(enableCache && jsCache[url]){

document.getElementById(divId).innerHTML = jsCache[url];

return;

}

var ajaxIndex = dynamicContent_ajaxObjects.length;

document.getElementById(divId).innerHTML = ‘Loading content – please wait';

dynamicContent_ajaxObjects[ajaxIndex] = new sack();

if(url.indexOf(‘?’)>=0){

dynamicContent_ajaxObjects[ajaxIndex].method=’GET';

var string = url.substring(url.indexOf(‘?’));

url = url.replace(string,”);

string = string.replace(‘?’,”);

var items = string.split(/&/g);

for(var no=0;no<items.length;no++){

var tokens = items[no].split(‘=’);

if(tokens.length==2){

dynamicContent_ajaxObjects[ajaxIndex].setVar(tokens[0],tokens[1]);

}

}

url = url.replace(string,”);

}

dynamicContent_ajaxObjects[ajaxIndex].requestFile = url;            // Specifying which file to get

dynamicContent_ajaxObjects[ajaxIndex].onCompletion = function(){ ajax_showContent(divId,ajaxIndex,url); };            // Specify function that will be executed after file has been found

dynamicContent_ajaxObjects[ajaxIndex].runAJAX();                      // Execute AJAX function

}

EXTERNAL FILE TO SHOW CONTENTS

When having the <a> tag href is like the below,

‘search_contentfile.php?Id=<dynamic idno>’ then search_contentfile.php is the external file name.

The Page  can be designed as per purpose, but the contents need to show must be followed by echo statement

Sample External File

<?

include’library/config.php';

include’library/opendb.php';

include’library/constants_path.php';

include’library/functions.php';

$description=”;

$cats_id = 0;

if(isset($_GET[‘ad_id’]) && $_GET[‘ad_id’]!=”)

{

$get_details_query = “select * from ads where ad_id=’$_GET[ad_id]'”;

$get_details_result = mysql_query($get_details_query);

$get_rows = mysql_fetch_array($get_details_result);

$description = str_replace(“/n”,”<br/>”,$get_rows[‘ad_description’]);

$contact_email = $get_rows[‘Contact_email’];

$con = $get_rows[‘date_posted’];

$dates     = explode(“-“, $con);

$year     = $dates[‘0′];

$month     = $dates[‘1′];

$day      = $dates[‘2′];

$Date = date(“d-M-Y”, mktime(0,0,0,$month, $day, $year));

//—————–   PRICE  ————————

$Price = $get_rows[‘price’];

$category_id = $get_rows[‘category_id’];

if($category_id != ”&& $category_id != 0)

{

$cat_query = “select * from categories where category_id = $category_id and par_category_id IS NULL”;

$cat_result = mysql_query($cat_query);

$cat_num_row = mysql_num_rows($cat_result);

$cat_row = mysql_fetch_array($cat_result);

if($cat_num_row == 0)

{

$subcat_query = “select * from categories where category_id = $category_id”;

$subcat_result = mysql_query($subcat_query);

$subcat_row = mysql_fetch_array($subcat_result);

$cats_query = “select * from categories where category_id = $subcat_row[par_category_id]”;

$cats_result = mysql_query($cats_query);

$cats_row = mysql_fetch_array($cats_result);

$cats_id = $cats_row[‘category_id’];

}

else

{

$cats_id = $cat_row[‘category_id’];

}

}

//—————–   PRICE  ————————

$output = ”        <html>

<body>

<table border=0 width=100%>

<tr>

<!–       <td align=left width=50%><b>Email: $contact_email</b></td>            –>

<td align=left width=50%>&nbsp;<b>”;

if($cats_id==1 || $cats_id==2 || $cats_id==109)

{

$output .=”                                                                                <b>Price: Rs$Price</b>”;

}

$output .= ”                                                       </td>

<td align=left width=15%>&nbsp;</td>

<td align=right width=35%><b>Date: $Date</b>&nbsp;</td>

</tr>

<tr>

<td colspan=3></td>

</tr>

<tr>

<td colspan=3>$description;</td>

</tr>

</table>

</body>

</html>”;

echo $output;

}

else

{

echo “”;

}

?>

CSS FILE:

The Styles for the Css is defined as

#ajax_tooltipObj{

font-family: Calibri;

z-index:1000000;

text-align:left;

}

#ajax_tooltipObj div{

position:relative;

}

/* If you don’t want the arrow – Just set the width of this div to 1 or something like that and drop the background selectors from the CSS below */

#ajax_tooltipObj .ajax_tooltip_arrow{        /* Left div for the small arrow */

background-image:url(‘../images/ajaxarrow.gif’);

width:20px;

position:absolute;

left:0px;

top:0px;

background-repeat:no-repeat;

background-position:center left;

z-index:1000005;

height:40px;

}

#ajax_tooltipObj .ajax_tooltip_content{

border:2px solid #317082;           /* Border width */

left:18px;           /* Same as border thickness */

top:0px;

position:absolute;

width:400px;      /* Width of tooltip content */

height:auto;       /* Height of tooltip content */

background-color:#FFF;  /* Background color */

padding:5px;      /* Space between border and content */

font-size:0.8em; /* Font size of content */

font-family: Calibri;

overflow:auto;     /* Hide overflow content */

z-index:1000001;

}

Customizing the Tool tip:

We can customize the tool tip by altering the css codes. We can change the appearance of the tool tip box,

Example from droik.com search result:

Ajax Dynamic Tool Tip

Above snapshot shows the description about the advertisement dynamically to the user.

Conclusion:

Showing tooltip will be very good idea during website designs, and its give the idea about the link for the users. And also its easy to use and efficient.

Categories: Uncategorized Tags:
  1. flam
    February 28th, 2012 at 21:40 | #1

    Hiii… Im beginner in ajax tooltip, would you teach me how to set “width” for tooltip?

  2. April 15th, 2010 at 07:07 | #2

    @venkat
    In Skill-Guru you can find all types of questions on java ,j2ee , spring and hibernate.
    Anything specifically your are looking for ?

  3. April 15th, 2010 at 05:14 | #3

    hi sir this is venkat….

    i want all types of j2EE multiple choice questions… can u please help me on this…..

    if u want more clarity on this issue… please … call me : 9030274771 (or) oneguyvenkat007@gmail.com

  1. April 10th, 2010 at 15:15 | #1