Search code examples
javascripthtmlcsstooltip

JS: Relative positioning of tooltip on right of icon


I have an icon, and when you hover over it, I would like to have a custom CSS tooltip appear to the right of the icon. Whether or not you scroll up or down the page, the tooltip will always need to appear to the right of the icon.

And no, I don't want to use any plugins. I just want a little JS/CSS to get the job done. If you use JQuery, it needs to be compatible with v1.7, and JQuery-UI: v1.8.

In addition, it needs to be compatible with IE 6 and 7.

I would prefer to leave my elements as siblings, but it looks like under certain circumstances the div that appears needs to be a child element, so it's OK if the HTML needs to be changed.

HTML:

<img src="" class="icon">ICON<img/>

<div class="demo">
    STUFF<br/>
    STUFF<br/>
    STUFF<br/>
    STUFF<br/>
    STUFF<br/>
</div>

CSS:

.demo {
    margin-left: 5px;
    padding: 10px;
    width: 265px;
    height: 110px;
    background-color: #ccc;
    position: relative;
    border: 2px solid #333;
}

.demo:after, .demo:before {
    border: solid transparent;
    content: ' ';
    height: 0;
    right: 100%;
    position: absolute;
    width: 0;
}

.demo:after {
    border-width: 11px;
    border-right-color: #ccc;
    top: 13px;
}

.demo:before {
    border-width: 14px;
    border-right-color: #333;
    top: 10px;
}

Live Example: http://jsfiddle.net/49Js3/16/


Solution

  • Fiddle here: http://jsfiddle.net/49Js3/29/

    I don't have access to IE6, so I don't know whether it's legal. I do know you'll need an anchor to get hover behavior with CSS in IE7 and earlier.

    So, I added an anchor around your image, as well as a div to contain the tooltip.

    HTML

    <div class="outer">
    <a class="tippy" href="">
            <img src="" class="icon">ICON<img/>
       </a>
    
        <div class="demo">STUFF
            <br/>STUFF
            <br/>STUFF
            <br/>STUFF
            <br/>STUFF
            <br/>
        </div>
    </div>
    

    And here is the CSS:

    .tippy {
        text-decoration: none;
    }
    .outer {
        width: 350px;
    }
    a.tippy:hover + div {
        display:block;
        float: right;
    }
    .demo {
        margin-left: 5px;
        padding: 10px;
        width: 265px;
        height: 110px;
        background-color: #ccc;
        position: relative;
        border: 2px solid #333;
        display: none;
    }
    .demo:after, .demo:before {
        border: solid transparent;
        content:' ';
        height: 0;
        right: 100%;
        position: absolute;
        width: 0;
    }
    .demo:after {
        border-width: 11px;
        border-right-color: #ccc;
        top: 13px;
    }
    .demo:before {
        border-width: 14px;
        border-right-color: #333;
        top: 10px;
    }