Hover over div

Task: I have a div with a fixed size and no scroll bars. Because of this, when the content exceeds the size of the div, parts of it will not be displayed. In this case I want to see the complete div content when I hover over it (something like a tool tip). Otherwise, when the div displays all it’s contents, no hover over div will be shown.See demo

Implementation:

  • HTML
    <a class="hoverOver">
        <div class="hoverOverSmall" >This div contains more text than it can show -> show the image and the details on hover.
        </div>
    </a>
    
  • CSS
    .hoverOver {
        position: relative;
        z-index: 0;
    }  
    .hoverOver div.hoverOverSmall {
        position : relative;
        overflow:hidden; 
        width:150px; 
        height:22px;
        overflow: hidden;
        border: 1px solid #e6e6e6;
    }
    span.hoverOverDetailsImage{
        position:absolute;
        top:0;
        right:2px;
        display:inline-block;
        width:22px;
        height:22px;
        background: url(https://codeutil.files.wordpress.com/2011/11/search-icon.png) no-repeat top right;
        z-index:100;
        background-color: #fff;
    }
    div.hoverOverLarge {
        position: absolute;
        display:none;
        z-index:101;
        border: 1px solid #fff; 
        background-color: #e6e6e6;
        color: #333;
        padding: 5px;
        width: 250px;
        height: auto;
        overflow: auto;
    }
    
  • Javascript

    $('.hoverOverSmall').each(function(index) {
        if (this.scrollHeight > $(this).height() || this.scrollWidth > $(this).width()) {
            var details = $('<div class="hoverOverLarge">' + this.innerHTML + '</div>');
            $("body").append(details);
    
            $(this).append("<span class='hoverOverDetailsImage'>&nbsp;</span>");
    
            $(this).bind('mouseenter', {
                smallDiv: $(this),
                detailsDiv: details
            }, hoverOverEnter);
    
            $(this).bind('mouseleave', {
                detailsDiv: details
            }, hoverOverLeave);
        }
    });
    
    function hoverOverEnter(event) {
        var position = event.data.smallDiv.offset();
        position.top += 20;
        position.left += 20;
        event.data.detailsDiv.css(position);
        event.data.detailsDiv.css('display', 'block');
    };
    
    function hoverOverLeave(event) {
        event.data.detailsDiv.css('display', 'none');
    };
    
Advertisements