0

I am trying this code but i get: document.getElementsByName(...).style is undefined

I have also a problem with the delegation, i think. Any help?

<html>
    <head>
    <style type="text/css">
    #toolTip {
        position:relative;
        width:200px;
        margin-top:-90px;
    }

    #toolTip p {

        padding:10px;
        background-color:#f9f9f9;
        border:solid 1px #a0c7ff;
        -moz-border-radius:5px;-ie-border-radius:5px;-webkit-border-radius:5px;-o-border-radius:5px;border-radius:5px;
    }

    #tailShadow {
        position:absolute;
        bottom:-8px;
        left:28px;
        width:0;height:0;
        border:solid 2px #fff;
        box-shadow:0 0 10px 1px #555;
    }

    #tail1 {
        position:absolute;
        bottom:-20px;
        left:20px;
        width:0;height:0;
        border-color:#a0c7ff transparent transparent transparent;
        border-width:10px;
        border-style:solid;
    }

    #tail2 {
        position:absolute;
        bottom:-18px;
        left:20px;
        width:0;height:0;
        border-color:#f9f9f9 transparent transparent transparent;
        border-width:10px;
        border-style:solid;
    }
    </style>
    <script type='text/javascript'>
    function load () {
            var elements = document.getElementsByName('toolTip');
            for(var i=0; i<elements.length; i++) {
                document.getElementsByName(elements[i]).style.visibility = 'hidden';
            }
        }
    </script>

    </head>



    <body onload="load()">
    <br><br><br><br><br><br><br><br><br><br><br><br>
    <a class="hd" 
    onMouseOver="document.getElementsByName('toolTip')[0].style.visibility = 'visible'"
    onmouseout ="document.getElementsByName('toolTip')[0].style.visibility = 'hidden'">aqui</a>
    <div id="toolTip" name="toolTip">
        <p>i can haz css tooltip</p>
        <div id="tailShadow"></div>
        <div id="tail1"></div>
        <div id="tail2"></div>
    </div>

    <br><br><br>
    <a class="hd" 
    onMouseOver="document.getElementsByName('toolTip')[0].style.visibility = 'visible'"
    onmouseout ="document.getElementsByName('toolTip')[0].style.visibility = 'hidden'">aqui</a>
    <div id="toolTip" name="toolTip">
        <p>i can haz css tooltip</p>
        <div id="tailShadow"></div>
        <div id="tail1"></div>
        <div id="tail2"></div>
    </div>

    </body>
    </html>

demo

1
  • You've got duplicate id's, which is impossible (an ID is, by definition unique) Dec 4, 2012 at 11:42

4 Answers 4

1

Try changing the id toolTip to a class:

<div class="toolTip">...</div>

And change your JS to use the display style-thing, rather than visibility, nd the onmouseover's are best dealt with using JS event delegation:

function load()
{
    var i, tooltips = document.getElementsByClassName('toolTip'),
    mouseOver = function(e)
    {//handler for mouseover
        e = e || window.event;
        var i, target = e.target || e.srcElement,
        targetToolTip = target.nextElementSibling || nextSibling;//gets the next element in DOM (ie the tooltip)
        //check if mouse is over a relevant element:
        if (target.tagName.toLowerCase() !== 'a' || !target.className.match(/\bhd\b/))
        {//nope? stop here, then
            return e;
        }
        targetToolTip.style.display = 'block';//make visible
        for (i=0;i<tooltips.length;i++)
        {//closures are neat --> you have a reference to all tooltip elements from load scope
            if (tooltips[i] !== targetToolTip)
            {//not the one you need to see
                tooltips[i].style.display = 'none';
            }
        }
    };
    for (i=0;i<tooltips.length;i++)
    {
        tooltips[i].style.display = 'none';
    }
    //add listener:
    if (document.body.addEventListener)
    {//IE > 9, chrome, safari, FF...
        document.body.addEventListener('mouseover',mouseOver,false);
    }
    else
    {//IE8
        document.body.attachEvent('onmouseover',mouseOver);
    }
}

Google JavaScript event delegation and closures if this code isn't clear, but that's just how I would tackle this kind of thing. IMO, it's fairly efficient (you could use the closure scope to keep track of the tooltip that's currently visible and not loop through all of them, too, that would be even better:

function load()
{
    var i, tooltips = document.getElementsByClassName('toolTip'),
    currentToolTip,//<-- reference currently visible
    mouseOver = function(e)
    {
        e = e || window.event;
        var i, target = e.target || e.srcElement,
        targetToolTip = target.nextElementSibling || nextSibling;

        if (target.tagName.toLowerCase() !== 'a' || !target.className.match(/\bhd\b/) || targetToolTip === currentToolTip)
        {//add check for currently visible TT, if so, no further action required
            return e;
        }
        if (currentToolTip !== undefined)
        {
            currentToolTip.style.display = 'none';//hide currently visible
        }
        targetToolTip.style.display = 'block';//make new visible
        currentToolTip = targetToolTip;//keep reference for next event
    };
    for (i=0;i<tooltips.length;i++)
    {
        tooltips[i].style.display = 'none';
    }
    if (document.body.addEventListener)
    {
        document.body.addEventListener('mouseover',mouseOver,false);
    }
    else
    {
        document.body.attachEvent('onmouseover',mouseOver);
    }
}

And you're there.

Edit:
To hide the tooltip on mouseout, you can either add a second listener directly:

function load()
{
    var i, tooltips = document.getElementsByClassName('toolTip'),
    currentToolTip,//<-- reference currently visible
    mouseOver = function(e)
    {
        e = e || window.event;
        var i, target = e.target || e.srcElement,
        targetToolTip = target.nextElementSibling || nextSibling;

        if (target.tagName.toLowerCase() !== 'a' || !target.className.match(/\bhd\b/) || targetToolTip === currentToolTip)
        {//add check for currently visible TT, if so, no further action required
            return e;
        }
        if (currentToolTip !== undefined)
        {
            currentToolTip.style.display = 'none';//hide currently visible
        }
        targetToolTip.style.display = 'block';//make new visible
        currentToolTip = targetToolTip;//keep reference for next event
    },
    mouseOut = function(e)
    {
        e = e || window.event;
        var movedTo = document.elementFromPoint(e.clientX,e.clientY);//check where the cursor is NOW
        if (movedTo === curentToolTip || currentToolTip === undefined)
        {//if cursor moved to tooltip, don't hide it, if nothing is visible, stop
            return e;
        }
        currentTooltip.style.display = 'none';
        currentTooltip = undefined;//no currentToolTip anymore
    };
    for (i=0;i<tooltips.length;i++)
    {
        tooltips[i].style.display = 'none';
    }
    if (document.body.addEventListener)
    {
        document.body.addEventListener('mouseover',mouseOver,false);
        document.body.addEventListener('mouseout',mouseOut,false);
    }
    else
    {
        document.body.attachEvent('onmouseover',mouseOver);
        document.body.attachEvent('onmouseout',mouseOut);
    }
}

Note, this is completely untested. I'm not entirely sure if IE < 9 supports elementFromPoint (gets the DOM element that is rendered at certain coordinates), or even if the IE event object has the clientX and clientY properties, but I figure a quick google will tell you more, including how to get the coordinates and the element that is to be found under the cursor in old, crummy, ghastly IE8, but this should help you on your way. Of course, if you don't want the contents of the tooltip to be selectable, just change the mouseOut function to:

mouseOut = function(e)
{
    e = e || window.event;
    var target = e.target || e.srcElement;
    if (currentToolTip)
    {
        currentToolTip.style.diplay = 'none';
        currentToolTip = undefined;
    }
};

No need to check if the mouseout was on the correct element, just check if there is a current tooltip, and hide it.

3
  • jsbin.com/imosiz/3/edit there is only a problem. The tooltip is persistent. Thanks!
    – anvd
    Dec 4, 2012 at 12:01
  • Oh, in that case, adding a second listener for an onmouseout event would do, I'll add a couple of suggestions Dec 4, 2012 at 12:03
  • @anvd: There you go, I've added 2 suggestion: one to not hide the tooltip if the cursor is on it, the other to hide the tooltip whenever the mouse leaves the anchor (well, it doesn't matter which element the client moving out of, if the tooltip is visible, it'll always be an anchor with class hd) Dec 4, 2012 at 12:19
0

Try using classes to mark the tooltips:

<div id="toolTip1" class="toolTip">
    <p>i can haz css tooltip</p>
    <div id="tailShadow"></div>
    <div id="tail1"></div>
    <div id="tail2"></div>
</div>

And JQuery to toggle the visibility using the class as the selector:

$('.toolTip').attr('visibility', 'hidden')

Definitely clean up the non-unique Id's - this will cause you no end of troubles otherwise

3
  • 2
    Where's the jQuery tag here? please, don't go about assuming the entire world uses jQuery. Some people just like to learn more about the way JS works Dec 4, 2012 at 11:51
  • Ok, I take your point about the lack of the tag, but at the same time the OP didn't specifically say they wanted a non-jQuery answer (and after all, jQuery is still JavaScript under the hood :) ). The jQuery solution is nonetheless a viable option, and in my view a more elegant one (provided of course the OP has no particular requirement to exclude jQuery) - up to the OP to decide I guess. Dec 4, 2012 at 12:05
  • 1
    Sure the OP specified he didn't want a jQ answer: the title of the question ("tooltip in pure JS") is quite clear about that. If the title were any different, you'd be absolutely right in saying jQ is a valid answer... BTW: Of course jQ is JS under the hood, but I am just one of those ppl that can't stand not knowing what happens under the bonnet :). Dec 4, 2012 at 12:22
0

Your problem is likely because you're using the same id for both the tooltips. This is invalid; an id should be unique -- only one element in a given page should have a specific ID.

If you need a shared identifier for multiple objects, use a class instead.

0

I built a tooltip with a border in pure js that doesn't use hover.

html

            <div id="infoId" class='info' style="font-variant:small-caps;text-align:center;padding-top:10px;">
                <span id="innerspanid">
                </span>
            </div>
        </div>
        <input id="startbtn" class="getstartedbtn" type="button" value="Start >" />
    </div>

js

function getTextWidth(text, font) {
    // re-use canvas object for better performance
    const canvas = getTextWidth.canvas || (getTextWidth.canvas = document.createElement("canvas"));
    const context = canvas.getContext("2d");
    context.font = font;

    const metrics = context.measureText(text);
    return metrics.width;
}
function getCssStyle(element, prop) {
    return window.getComputedStyle(element, null).getPropertyValue(prop);
}
function getCanvasFontSize(el = document.body) {
    const fontWeight = getCssStyle(el, 'font-weight') || 'normal';
    const fontSize = getCssStyle(el, 'font-size') || '16px';
    const fontFamily = getCssStyle(el, 'font-family') || 'Times New Roman';

    return `${fontWeight} ${fontSize} ${fontFamily}`;
}

let arrowDimensionWidth = 20;
let arrowDimensionHeight = 20;
let tooltipTextHorizontalMargin = 50;

function openTooltip(text) {

    let innerSpan = document.getElementById("innerspanid");
    innerSpan.innerHTML = text;
    let computedW = getTextWidth(text, getCanvasFontSize(innerSpan)) + tooltipTextHorizontalMargin;

    let pointer = document.getElementById('pointer')
    pointer.style.right = (((computedW / 2) - (arrowDimensionWidth / 2)) - (0)) + 'px';

    let elem = document.getElementById('tooltipHost').parentNode.querySelector('div.info_container');
    elem.style.left = ((tooltipHost.getBoundingClientRect().width - computedW) / 2) + "px";
    elem.style.width = computedW + "px";
    elem.style.display = 'block';
}

function buildTooltip() {

    let elements = document.querySelectorAll('div.tooltip');

    // Create a canvas element where the triangle will be drawn
    let canvas = document.createElement('canvas');
    canvas.width = arrowDimensionWidth; // arrow width
    canvas.height = arrowDimensionHeight; // arrow height
    let ctx = canvas.getContext('2d');
    ctx.strokeStyle = 'darkred';   // Border color
    ctx.fillStyle = 'white';     // background color
    ctx.lineWidth = 1;
    ctx.translate(-0.5, -0.5);   // Move half pixel to make sharp lines
    ctx.beginPath();
    ctx.moveTo(1, canvas.height);              // lower left corner
    ctx.lineTo((canvas.width / 2), 1);              // upper right corner
    ctx.lineTo(canvas.width, canvas.height);   // lower right corner
    ctx.fill();                               // fill the background
    ctx.stroke();                             // stroke it with border
    ctx.fillRect(0, canvas.height - 0.5, canvas.width - 1, canvas.height + 2); //fix bottom row

    // Create a div element where the triangle will be set as background
    pointer = document.createElement('div');
    pointer.id = "pointer"
    pointer.style.width = canvas.width + 'px';
    pointer.style.height = canvas.height + 'px';
    pointer.innerHTML = '&nbsp;' // non breaking space
    pointer.style.backgroundImage = 'url(' + canvas.toDataURL() + ')';
    pointer.style.position = 'absolute';
    pointer.style.top = '2px';
    pointer.style.zIndex = '1'; // place it over the other elements

    let idx;
    let len;
    for (idx = 0, len = elements.length; idx < len; ++idx) {
        let elem = elements[idx];
        let text = elem.querySelector('div.info');
        let info = document.createElement('div');
        text.parentNode.replaceChild(info, text);
        info.className = 'info_container';
        info.appendChild(pointer.cloneNode());
        info.appendChild(text);
    }
}
window.addEventListener('load', buildTooltip);

window.addEventListener('load', wireup);

        function wireup() {
            document.getElementById('startbtn').addEventListener('click', function (evt1) {
                openTooltip("bad email no @ sign");
                return false;
            });
        }

css

div.tooltip {
    position: relative;
    display: inline-block;
}

    div.tooltip > div.info {
        display: none;
    }

    div.tooltip div.info_container {
        position: absolute;
        left: 0px;
        width: 100px;
        height: 70px;
        display: none;
    }

    div.tooltip div.info {
        position: absolute;
        left: 0px;
        text-align: left;
        background-color: white;
        font-size: 18px;
        left: 1px;
        right: 1px;
        top: 20px;
        bottom: 1px;
        color: #000;
        padding: 5px;
        overflow: auto;
        border: 1px solid darkred;
        border-radius: 5px;
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.