Implement a mouseover event on the axis label using D3.js and JavaScript

Is it possible to trigger a mouseover event on the y-axis label in a chart? For instance, let's say we have a scatter plot with labels "area1", "area2", and "area3" on the y-axis. When a user hovers over the label "area1", a tooltip should appear displaying the description of area1. I haven't come across any examples of this. Does anyone know how to achieve this? Thank you!
I've also created a plunker that can be accessed here

<!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <title>Plot</title>
    <style> 
     .axis path,
     .axis line{
        fill: none;
        stroke: #000;
        shape-rendering: crispEdges;
        }    
    </style>
  </head>
    <h1 style = "text-align:center;">Example</h1>     

 <body>
    <script src="http://d3js.org/d3.v3.min.js"></script>  
    <div id="chart">
    </div>
    <script>

     var data = [
       {x: 5, y: "area1"
        },
       {x: 34, y: "area2"
        },
       {x: 19, y: "area3"
        }
       ];

 data.forEach(function(d){
        d.x = +d.x;
        d.y = d.y;

        return console.log(data);
    })

    var m = {t:30, r:20, b:40, l:45 },
        w = 600 - m.l - m.r,
        h = 500 - m.t - m.b;

    var x = d3.scale.linear()
        .range([0, w])
        .domain([0,d3.max(data, function(d){return d.x})]);

    var y = d3.scale.ordinal()
        .rangeRoundPoints([h-18,0])
        .domain(data.map(function(d){return d.y;}));   

    var xAxis = d3.svg.axis()
        .scale(x)
        .orient("bottom")
        .ticks(8);

    var yAxis = d3.svg.axis()
        .scale(y)
        .orient("left")
        .ticks(3);

    var svg = d3.select("#chart")
        .append("svg")
        .attr("width", w + m.l + m.r)
        .attr("height", h + m.t + m.b)
        .style("margin-left", "auto")
        .style("margin-right", "auto")
        .style("display", "block")
        .append("g")
        .attr("transform", "translate(" + m.l + "," + m.t + ")");     

    var circles = svg.selectAll("circle")
       .data(data)
       .enter()
       .append("circle")
       .attr("class", "circles")
       .attr({
        cx: function(d) { return x(d.x); },
        cy: function(d) { return y(d.y); },
        r: 8
      });

    svg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + h + ")")
        .call(xAxis);

    svg.append("g")
        .attr("class", "y axis")
        .call(yAxis);

    </script>
  </body>
</html>

Answer №1

To start, begin by creating a div element for the tooltip.

  var tooltipDiv = d3.select("body").append("div") 
    .attr("class", "tooltip")               
    .style("opacity", 0);

Then, specify the style for the tooltip in the CSS.

div.tooltip {
  position: absolute;
  text-align: center;
  width: 60px;
  height: 28px;
  padding: 2px;
  font: 12px sans-serif;
  background: lightsteelblue;
  border: 0px;
  border-radius: 8px;
  pointer-events: none;
}

For displaying the tooltip on the y-axis, attach mouseover and mouseout event listeners to all ticks.

yaxis.selectAll(".tick")[0].forEach(function(tick) {
    var data = d3.select(tick).data();
    d3.select(tick).on("mouseover", function(d) {
            tooltipDiv.transition()        
                .duration(200)      
                .style("opacity", .9);      
            tooltipDiv.html(data) 
                .style("left", (d3.event.pageX) + "px")     
                .style("top", (d3.event.pageY - 28) + "px");    
            })                  
        .on("mouseout", function(d) {   
            tooltipDiv.transition()        
                .duration(500)      
                .style("opacity", 0);   
        });
})

Check out the working code here.

I hope this explanation is useful!

Answer №2

There's a different approach to incorporating tool-tips into d3 graphs, utilizing svg:title elements.

Each SVG container element or graphics element within a drawing can provide a title description that is strictly text-based. While the title element isn't rendered with the graphics when the SVG document is displayed visually, certain user agents may choose to display it as a tooltip.

Edit:

If the tool-tip content is lengthy, you can insert \n at specific points to break it into multiple lines.

Assume your dataset includes descriptions like those below.

 var data = [{
     x: 5,
     y: "area1",
     desc: 'description 1'
 }, {
     x: 34,
     y: "area2",
     desc: 'description 2'
 }, {
     x: 19,
     y: "area3",
     desc: 'description 3'
 }];

You can implement tooltips as illustrated in the code snippet below.

svg.select(".y.axis")
    .selectAll(".tick")
    .append("svg:title")
    .text(function(d, i) {
        return data[i].desc //Alternatively, provide a customized description
    });
....

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The most effective method for monitoring updates to an array of objects in React

Imagine a scenario where an array of objects is stored in state like the example below: interface CheckItem { label: string; checked: boolean; disabled: boolean; } const [checkboxes, setCheckboxes] = useState<CheckItem[] | undefined>(undefined ...

What is the correct way to invoke a function within jQuery?

There must be a straightforward solution to what appears to be a simple and regular task. Inside the $(document).ready() function, I aim to invoke a function with a jQuery object - specifically without attaching it to an asynchronous event like mouseover ...

How to define an index signature in Typescript that includes both mandatory and optional keys

I am on a quest to discover a more refined approach for creating a type that permits certain keys of its index signature to be optional. Perhaps this is a scenario where generics would shine, but I have yet to unlock the solution. At present, my construc ...

Positioning Images in Tailwind Modals

I'm currently working on building a modal using Tailwind in Vue, but I've run into some challenges with aligning the elements inside the modal as desired. I've experimented with removing certain Tailwind classes and have tried implementing ...

What is the best way to eliminate a particular item from an array that is nested within the object? (using methods like pop() or any

I am struggling to remove the 'hello5' from the years in myObj. Although I tried using the 'pop' prototype, an error occurred in the browser console displaying: 'Uncaught TypeError: Cannot read property 'type' of undefi ...

Error: The JavaScript SRC cheat is malfunctioning

Having an issue with the code below. The 'dummy1' and 'dummy2' variables are not loading their content as expected on the page. Any suggestions? <html> <head> <title>JavaScript On-line Test</title> <script LA ...

Presentation with multi-directional animations

Curious to know if it's possible to create a unique slideshow that scrolls in multiple directions? The concept is to display various projects when scrolling up and down, and different images within each project when scrolling left and right. Is this i ...

After manipulating the array, Vue fails to render the input fields generated by the v-for directive

After setting the value externally, Vue component won't re-render array items. The state changes but v-for element does not reflect these changes. I have a component that displays items from an array. There are buttons to adjust the array length - &a ...

Are the results displayed in a vertical array format?

Being new to this world, I would greatly appreciate any assistance! I am working with Bootstrap checkboxes and trying to print them using jQuery's window.print function. However, the issue I am facing is that the array I create from the checkboxes d ...

Tips for incorporating Javascript Object Literals into Python code

Using the Beautifulsoup module, I successfully extracted an HTML page and then proceeded to extract a Javascript script tag from that page. Within this script tag lies an object literal that I hope to manipulate. Here is what I am aiming for: <script&g ...

The drawback of invoking an async function without using the await keyword

Here is the code snippet containing an async function: async function strangeFunction(){ setTimeout(function(){ //background process without a return //Playing Russian roulette if ( Math.random() > 0.99 ) throw n ...

When submitting a form in HTML, ensure that the input checkbox returns 'On' instead of 'True'

My MVC3 app is using Project Awesome from http://awesome.codeplex.com/, but I'm encountering a strange issue with checkboxes. Inside a Modal popup, I have the following simple Html code: <input type="checkbox" class="check-box" name="IsDeleted"> ...

Unable to add chosen elements to array - Angular material mat select allowing multiple selections

Can anyone assist me in figuring out what I am doing wrong when attempting to push data to an empty array? I am trying to only add selected values (i.e. those with checked as true), but I can't seem to get inside the loop This is the current conditi ...

Send a value to several PHP pages simultaneously using JQuery

I find myself asking this question due to my lack of experience. Is it possible to send a value to multiple PHP pages using JQuery? Let me illustrate what I am attempting to achieve. $(function() { $("#account").change(function() { $("#facilities" ...

Change the display of the lightbox when clicked. Utilize Angular and JQuery for this functionality

Here is the code for a lightbox: <div id="light-box"> <div id="first"> ..... </div> //initially visible <div id="second"> ..... </div> //hidden - but displayed when button is clicked. </div> I want to add two button ...

Executing javascript functions from various HTML tags

The code snippet below is what I currently have: <script src="jquery-1.10.2.min.js"></script> <script> $('#year li').click(function() { var text = $(this).text(); //alert('text is ' + text); $.post("B.php" ...

Running NodeJS scripts with ElectronJS is not possible

Goal I'm facing a challenge with executing my separate scripts located in the project/api folder. Let's take test.js as an example, where I am exporting it using module.exports. When I run my electron window and create a JavaScript file with a f ...

I'm facing an issue with binding keyboard events in Vue - any suggestions on how to resolve

Hello everyone! I'm a newcomer to the world of Vue. Recently, I encountered an issue with keyboard-event binding that has left me puzzled. Let me share the relevant code snippet below: ...other code... <template v-for="(ite ...

Is it possible to modify the icon displayed in an AJax response?

I have a link with an icon inside that I need to change when it is clicked. To achieve this, I attempted to use Ajax in the following manner: HTML <a id="#pl-esong234" class="social-button-song" title="Add in playlist" onclick="addInPlaylistSongs(234, ...

Unable to access property 'map' of undefined - having trouble mapping data retrieved from Axios request

When working with React, I have encountered an issue while trying to fetch data from an API I created. The console correctly displays the response, which is a list of user names. However, the mapping process is not functioning as expected. Any insights or ...