Search code examples
javascriptcssfirefoxd3.jstooltip

Javascript tooltip cross browser incompatability


Greetings fellow coders!

I am working on a cool project in d3.js. Currently i am trying to make a tooltip work because in chrome it does not display the title attribute as a normal tooltip.

I found 2 solutions on the internet:

-Displaying the span of an element in a seperate box. I didn't seem to get this to work in my project.

-Using d3 to append a div to the svg so that a floating box of text appears next to the mouse. I managed to make this work, but only in chrome. If i do this in firefox, the box will appear in the bottom left. I even tried d3.mouse(this) for the coordinates but it just pops up at unexpected places.

In the fiddle, you can see both "solutions".

http://jsfiddle.net/fbba7u8h/5/

ps. firefox seemed to have trouble with the "event" thingy.

//square is defined in HTML, the red circle is made in js d3 code The javascript:

  d3.select("#square") 
    .on("mouseover", function(){return tooltip.style("visibility", "visible");})
    .on("mousemove", function(){return tooltip.style("top", (event.pageY-10)+"px").style("left",(event.pageX+10)+"px");})
    .on("mouseout", function(){return tooltip.style("visibility", "hidden");});

var tooltip = d3.select("body")
.append("div")
.attr("class", "halloTip")
.text("this is a tooltip using d3 js, in chrome it hovers next to mouse, in firefox it pops up in the bottom left! I also tried d3.mouse(this)[0] and [1] at the onMouseMove");

//the css style:

.halloTip{
    position:absolute;
    z-index:10;
    visibility:hidden;
    text:qqq;   
    background-color:rgb(5, 225, 153);
    stroke:black;   
    padding:11px;
}
.halloTip:hover{
    visibility:hidden;
    stroke-opacity:0.8; 
}

Solution

  • Try refering to d3.event instead of event.

    .on("mousemove", function(){ ... d3.event.pageY ... }
    

    If this also doesn't work then try a workaround ... something like:

    var mouse = { x: 0, y: 0 };
    document.addEventListener("mousemove", function(e) {
        mouse.x = e.pageX;
        mouse.y = e.pageY;
    });
    

    And then refer to mouse.x/mouse.y in the other callbacks