Thursday, July 16, 2009

JavaScript & DHTML Tooltips

Sometimes with a lot of links on your webpage you need to display a small description about the link targets. HTML supports title attribute for links which is displayed as tooltip, but it is not customizable and most browsers takes a while to display it. I have created an easy to use DHTML tooltip script for HTML links which requires no extra coding at all. For displaying tooltip for a certain link you just need to include a tooltip attribute in that link, rest everything is handled by the JavaScript code. For Example:

<a href="" tooltip="Your tooltip text goes here">Your Link</a>

I have designed the tooltip script in such a manner that it automatically scans all the links with tooltip attribute when the page loads for the first time and assigns mouse events to all those links. The tooltip is always displayed at the bottom right corner of the link text/image. If there is not enough space to the right or bottom of the link, the tooltip is moved to left or top corner of the link text accordingly. This is how the tooltips are displayed on the page:

JavaScript DHTML Tooltips

Because it is an automated and generic script, all the tooltips on a page will be of same color, style and width. To change the width of your tooltips, you can modify the value of the variable TooltipWidth in the JavaScript code. You can place the JavaScript code into the head section of your page or a separate file. Here is the JavaScript code for the tooltips:

<script type="text/javascript">
var EventUtil = {
    addHandler: function(element, type, handler) {
        if (element.addEventListener) {
            element.addEventListener(type, handler, false);
        } else if (element.attachEvent) {
            element.attachEvent("on" + type, handler);
        } else {
            element["on" + type] = handler;
        }
    }
};

var TooltipWidth = 200; // set width for the tooltip
var Tooltip =
{
    init: function() {
        var links = document.getElementsByTagName("a"); // scan all the links
        for (var i = 0; i < links.length; i++) {
            var tooltip = links[i].getAttribute("tooltip"); // get tooltip attribute
            if (tooltip && tooltip.length > 0) // if tooltip attribute exists
            {     // assign events to links with tooltips
                document.links[i].onmouseover = function() { Tooltip.showTip(this); };
                document.links[i].onfocus = function() { Tooltip.showTip(this); };
                document.links[i].onmouseout = function() { Tooltip.hideTip(); };
                document.links[i].onblur = function() { Tooltip.hideTip(); };
            }
        }
    },
    showTip: function(mylink) { // show tooltip
        Tooltip.hideTip(); // hide existing tooltips
        // create tooltip div
        var tooltip_div = document.createElement("div");
        tooltip_div.id = "mytooltip";
        tooltip_div.className = "tooltip";
        tooltip_div.style.width = TooltipWidth + "px";
        document.body.appendChild(tooltip_div);
        tooltip_div.innerHTML = mylink.getAttribute("tooltip");
        tooltip_div.style.left = Tooltip.tipX(mylink.offsetLeft, mylink.offsetWidth, tooltip_div.offsetWidth) + "px";
        tooltip_div.style.top = Tooltip.tipY(mylink.offsetTop, mylink.offsetHeight, tooltip_div.offsetHeight) + "px";
    },
    hideTip: function() { // hide tooltip
        var tooltip_div = document.getElementById("mytooltip");
        if (tooltip_div) document.body.removeChild(tooltip_div);
    },
    tipX: function(offLeft, offWidth, TooltipWidth) { // X coordinate of tooltip
        return ((offLeft + offWidth + TooltipWidth) > PageWidth()) ? offLeft - TooltipWidth : offLeft + offWidth;
    },
    tipY: function(offTop, offHeight, TooltipHeight) { // Y coordinate of tooltip
        return ((offTop + offHeight + TooltipHeight) > PageHeight()) ? offTop - TooltipHeight : offTop + offHeight;
    }
};

function PageWidth() { // return Page Width
    return window.innerWidth ? window.innerWidth : document.documentElement ? document.documentElement.clientWidth : document.body ? document.body.clientWidth : 0;
}
function PageHeight() { // return Page Height
    return window.innerHeight ? window.innerHeight : document.documentElement ? document.documentElement.clientHeight : document.body ? document.body.clientHeight : 0;
}
// Instantiate Tooltip event on window load
EventUtil.addHandler(window, "load", Tooltip.init);
</script>

Here is the CSS code for the tooltip, you can modify this to suit the color and styling of your website:

<style type="text/css">
<!--
.tooltip {
      position: absolute;
      background-color: #FFFFD9;
      border: 1px solid #FC0;
      padding: 5px;
      font-family: Verdana, Geneva, sans-serif;
      font-size: x-small;
      color: #930;
      text-align: justify;
}
-->
</style>

For simplicity I have positioned the tooltips relative to the link location on the page. To display it at the exact mouse location you can pass the event variable to the Tooltip.showTip function and display the tooltip at event.clientX and event.clientY position.

Technorati Tags: ,

3 comments:

  1. Guaranteed #1 Search Engine Ranking Supreme Free Viral Traffic Join Now Get Millions Of Hits Free To Your Site/Blog!

    PornKings Adult Shopping Backlinks-Shopping Mega Store Legendary Stars As Stormy Daniels,Shawna Edwards,Jenna Jamison-New Adult Stars Movies,Adult Toys,Enhancers,Merchandise-More !

    Hits Express Rotator System Do You Need Visitors to Your Website or Affiliate Program? If your looking to gain more visitors to your website Hits Express is your answer. With our program your site is being shown to people all over the world 24/7 365 days a year!

    PAYDIR Free For All Forum Portal Search Engine Crawled Network PR10 Ranking Information Forum XXX!

    FreeLinkExchanges Be Seen In 12 Nations 312 Sites Over 30 Millions Viewers Monthly Buy Featured Link Now With 150 Search Engines Crawling The Network!

    How do I get guaranteed traffic? When someone signs up from your site, they must first click on your classified ad which will open a new window leading to your main website. They will have to wait a few seconds for the code to appear on a separate frame at the top of the screen reach millions free now!

    Blast Your Ad to Over 23,000 Opt-in Prospects at ShowMyLinks Submit Your Solo Email Ad to All Showmylinks Members GET YOUR TEXT LINK ADs LISTED 100% FREE FOR LIFE PLUS EARN MONEY TO YOUR PAYPAL!!

    Adult Store Empires Backlinks Resources Search Engine XXX!

    GET YOUR OWN MONEY-MAKING AD BOARD -- Integrating Text ad, Banner Ad and Email Ad into one Portal Make Money Fast With Your Paypal Reach Million Dollars In A Year Fast !

    Full Length Homemade Videos Watch real people's private home sex videos. Forget about those shitty 1-2 minute clips, these are all high quality full length videos! 40+ Bonus Sites You will also get full access to the entire reelpass network of sites which features over 40+ awesome movie sites, 1000's of movies and pictures to download! Download, Burn & Share Not only do you get to watch all our movies, you can also download every single one and save it forever, burn them to dvd or share with friends!!

    ReplyDelete

Thanks a lot for your valuable comments :)