Home > Software design >  How do I permanently select a line with the click event in d3?
How do I permanently select a line with the click event in d3?

Time:11-08

I have multi-line graph where I want to click on a line and permanently highlighted it. I am using the following code with the click event, however after I click and move the mouse, the line goes back.

Hope someone could help me!

EDIT: I also have a mouseover and mouseout event that I included in the code snippet.

diagam.on('click', countryClick)
      .on('mouseover, countryOver)
      .on('mouseout, countryOut);

  //Mouse event functions
        function countryOver(event, d) {
            d3.select(this)
                .style('stroke', 'black')
                .style('stroke-width', 5)
                .attr('id', 'countryOver')
            .selectAll('g')
                .append('text')
                .attr('class', 'tile-text')
                .attr('x', x(dataByCountry.year) / 2)
                .attr('y', y(dataByCountry) / 2)
                .attr('text-anchor', 'middle')
                .attr('font-size', '50')
                .attr('fill', 'black')
                .text(dataByCountry.name);

        }

        function countryOut(event, ) { 
            d3.select(this)
                .style('stroke', 'green')
                .style('stroke-width', 1.5)
            .selectAll('g')
                .append('text')
                .attr('class', 'tile-text')
                .attr('x', x(dataByCountry.year) / 2)
                .attr('y', y(dataByCountry) / 2)
                .attr('text-anchor', 'middle')
                .attr('font-size', '50')
                .attr('fill', 'black')
                .text(dataByCountry.name)
        }

        function countryClick(event, d){
            d3.select(this)
            .style('stroke', 'red')
            .style('stroke-width', 7)
        .selectAll('g')
            .append('text')
            .attr('class', 'tile-text')
            .attr('x', x(dataByCountry.year) / 2)
            .attr('y', y(dataByCountry) / 2)
            .attr('text-anchor', 'middle')
            .attr('font-size', '50')
            .attr('fill', 'black')
            .text(dataByCountry.name)
        }

CodePudding user response:

If you want to highlight the line when the mouse is over it and also change its color when you click on it, you can use CSS to style the path depending on its state.

Take a look at this example: https://codepen.io/ccasenove/pen/zYaoGpN

Initially the paths only have the class line so we can select them using d3, and the color is set to black in CSS. On mouseover, the class over is set on the element which turns it green because of the CSS rule. On mouseout, the class over is removed. And when the path is clicked, the class selected is set to change the color to red.

  • Related