Search code examples
javascriptjqueryhtmlcsshoverintent

Hover direction according to container size


I would like to alter the hover direction based on the container size, if there's not enough space on the container to show the hover to the right, it should then show on the left.

See fiddle for details:

http://jsfiddle.net/jHgkp/3/

I use hoverIntent, but FULL details are on the Fiddle above:

            $(document).ready(function(){
                $(".discover").hoverIntent({
                over: makeVisible,
                out: makeInvisible,
                timeout: 200
                });
            }); // close document.ready

            function makeVisible() {
            $(this).find('ul').fadeIn(100);}
            function makeInvisible() {
            $(this).find('ul').fadeOut(300);}

Solution

  • There are a few approches.

    1) You can style the tooltip on the third element to show on the left side (not dynamic)

    2) You can take the element offest().left + element.width + the tooltip width and compare it with the holder width. (dynamic)

    3) Yo can the the tooltip offest + width and directly compare it to the holder width. (dynamic)

    It depends what exactly you want...

    This is the only JS added.

    var holderWidth = $('.container').outerWidth();
    

    and

    //where 260 is left 150 + width 110
    var pos = $(this).offset().left + 260
    if(holderWidth < pos){
        $(this).addClass('leftPos');
    }else{
        $(this).removeClass('leftPos');
    }
    

    and 1 line of css:

    .leftPos ul { left: auto; right: 150px; }
    

    Demo