Question

So I've been trying to integrate flot into some of our standard reporting stuff. I looked at some of the flot examples and cobbled together some code that generates a flot plot based on some data that we generate a report on.

From one of the flot examples, I found that you could make a tooltip appear over the graph through some javascript. It works great. My one issue, that I cannot seem to resolve, is with the tooltip. Occasionally, when the tooltip gets to be on the far right of the graph, such that it would render off the side of the page, it renders off the side of the page.

This is problematic because in order to clearly read the tooltip at that point you must scroll the page to the right, while keeping the mouse on the relevant data piece. To solve this I am trying to render the tooltip to the left of the cursor when the cursor would be past the left half of the plot area. However, I have so far only been successful at determining when the cursor is past the left half of the screen, and my attempts to reposition the div have been fruitless.

Relevant Code:

function showTooltip(x, y, msg) {
    flot_tooltip = $("<div id = 'flot_tooltip'>" + msg + '</div>').css({
        position: 'absolute',
        display: 'none',
        top: y + 5,
        left: x + 5,
        border: '1px solid #000',
        background: '#eee',
        padding: '2px',
        opacity: '0.75'
    }).appendTo('body').fadeIn(150)
    adjustForX(flot_tooltip)
}

function adjustForX(flot_tooltip){
    if ($(flot_tooltip).offset().left > window.innerWidth/2) {
        //alert($(flot_tooltip).width())
        //next need to adjust the left position of the element
    }
}

Full Fiddle

Sorry for the long-winded explanation, any guidance would be much appreciated.

Was it helpful?

Solution

I had the same problem on one of my pages and solved it with this code:

function showTooltip(x, y, contents) {
    var params = {
        position: 'absolute',
        display: 'none',
        border: '2px solid #333333',
        'border-radius': '3px',
        padding: '3px',
        size: '10',
        'background-color': 'lightyellow',
        opacity: 0.90
    };
    if (x < 0.8 * $(window).width()) {
        params.left = x + 20;
    }
    else {
        params.right = $(window).width() - x + 20;
    }
    if (y < 0.8 * $(window).height()) {
        params.top = y + 5;
    }
    else {
        params.bottom = $(window).height() - y + 10;
    }
    $('<div id="tooltip">' + contents + '</div>').css(params).appendTo('body').fadeIn(200);
}

Here I compare the xand yposition values to the window size and position the tooltip to the left of the mouse position if the mouse position is near the right border and above the mouse position if it is near the bottom.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top