$(document).ready(function() {
    $(".tip_trigger").hover(function(){
        $(this).find('.tip').show(); //Show tooltip
    }, function() {
        $(this).find('.tip').hide(); //Hide tooltip
    }).mousemove(function(e) {
          var mousex = e.pageX + 20; //Get X coodrinates
          var mousey = e.pageY + 20; //Get Y coordinates
          var tipWidth = $(this).find('.tip').width(); //Find width of tooltip
          var tipHeight = $(this).find('.tip').height(); //Find height of tooltip

         //Distance of element from the right edge of viewport
          var tipVisX = $(window).width() - (mousex + tipWidth);
         //Distance of element from the bottom edge of viewport
          var tipVisY = $(window).height() - (mousey + tipHeight);

        if ( tipVisX < 20 ) { //If tooltip exceeds the X coordinate of viewport (Exceeds the right side of viewport)
            mousex = e.pageX - tipWidth - 20; //Set new X coordinate
            $(this).find('.tip').css({  top: mousey, left: mousex }); //Move tooltip element to the left side
        } if ( tipVisY < 20 ) { //If tooltip exceeds the Y coordinate of viewport (Exceeds the bottom of the viewport)
            mousey = e.pageY - tipHeight - 20; //Set new Y coordinate
            $(this).find('.tip').css({  top: mousey, left: mousex }); //Move tooltip element on top
        } else { //By Default have the tooltip on the bottom right
            $(this).find('.tip').css({  top: mousey, left: mousex });
        }
    });
});
