RANGER Front-End Test - Pt. 5

by lasha

HTML

<ul>
    <li>Home</li>
    <li>Portfolio</li>
    <li>About</li>
    <li>Contact</li>
</ul>

<div class="tooltip">This is item 1</div>
<div class="tooltip">2nd item</div>
<div class="tooltip">Third item here is longer</div>

CSS

ul {
    margin: 0;
    padding: 0;
    width: 410px;
    margin: 0 auto;
}
li {
    display: inline-block;
    margin-right: 70px;
}
li:last-child {
    margin: 0;
}

.tooltip {
    position: absolute;
    z-index: 99;
    white-space: nowrap;
    background-color: #c8ffc8;
    padding: 7px 10px;
    font-size: 11px;
    font-family: Arial;
    word-spacing: 1px;
}

.tooltip:after {
    content: "";
    position: absolute;
    left: 50%;
    top: -15px;
    margin-left: -6px;
    width: 0px;
    height: 0px;
    border-style: solid;
    border-width: 0 6px 15px 6px;
    border-color: transparent transparent #c8ffc8 transparent;
}

JavaScript

/*
The goal of this exercise is to create some kind of a loop system, using either raw JavaScript or jQuery to detect the position, dimensions and so forth of each list item. Then, applying CSS directly to each of the tooltips to position them centered directly under their relative list item.
Requirement: The tooltips must stay in place when resizing the window.
*/

var $navItems = $("ul").find("li"),
    $tooltip = $(".tooltip");

$(window).on("resize", function(){
    runPositions();
}).resize();

function runPositions(){
    $tooltip.each(function(i, el){
        var $this = $(this),
            $currentNavItem = $navItems.eq(i),
            currentOffset = $currentNavItem.offset();
        
        $this.css({
            left: currentOffset.left + ($currentNavItem.width()/2) - $this.outerWidth()/2,
            top: currentOffset.top + 15 + $currentNavItem.height()
        });
    });
}