Search code examples
javascriptd3.jstooltiptipsy

Highlight elliptical arc drawn using D3.js on Mouseover and display tooltip


How do I highlight an elliptical arc drawn, on mouseover and display tooltip on the same using d3.js?


Solution

  • <!DOCTYPE html>
    <meta charset="utf-8">
    <html>
    <head>
        <style>
            body { font: 10px sans-serif; }
    
            .d3-tip {
                background: rgba(0, 0, 0, 0.8);
                border-radius: 2px;
                color: #fff;
                font-weight: bold;
                line-height: 1;
                padding: 12px;
            }
        </style>
    </head>
    <body>
    <script src="http://d3js.org/d3.v3.min.js"></script>
    <script src="http://labratrevenge.com/d3-tip/javascripts/d3.tip.v0.6.3.js"></script>
    <script>
    
        var w = window.innerWidth,
            h = window.innerHeight,
            margin = { top: 40, right: 20, bottom: 20, left: 40 };
    
        var svg = d3.select("body").append("svg").attr({
            width: w,
            height: h
        });
    
        var dataset = [
            { toolTip: "one", d: "M 50 200 a 100 50 0 1 1 250 50" },
            { toolTip: "two", d: "M 400 100 a 100 50 30 1 1 250 50" },
            { toolTip: "three", d: "M 400 300 a 100 50 45 1 1 250 50" },
            { toolTip: "four", d: "M 750 200 a 100 50 135 1 1 250 50" }
        ];
    
        var tip = d3.tip()
            .attr('class', 'd3-tip')
            .offset([-10, 0])
            .html(function(d) {
                return "<strong>Elipse:</strong> <span style='color:red'>" + d.toolTip + "</span>";
            });
    
        svg.selectAll("g")
            .data(dataset)
            .enter()
            .append("g")
            .attr("stroke-width", 3)
            .attr("stroke", "black")
            .attr("fill", "none")
            .on('mouseover', tip.show)
            .on('mouseout', tip.hide)
            .append("path")
            .attr("d", function(d) { return d.d })
            .on('mouseover', highLight)
            .on('mouseout', unHighLight);
    
            svg.call(tip);
    
        function highLight(){
           var foo = d3.select(this);
           foo.attr("stroke","red");
       }
    
        function unHighLight(){
            var foo = d3.select(this);
            foo.attr("stroke","black");
        }
    
    </script>
    </body>
    </html>
    

    view block here