What steps can be taken to ensure that specific elements stand out when they are clicked on

I'm in the process of creating a graph featuring bars with distinct data, color-coded for clarity. The legend explains the meaning behind each color. My goal is to implement a feature where clicking on a circle in the legend will highlight bars of the corresponding color on the graph.

<!DOCTYPE html>
<html>
<head>
  <meta>
  <meta name="description" content="Visualizing Resource Allocation per Project with Bar Graphs" />
  <meta charset="utf-8">
  <title>Resource Distribution by Program</title>
  <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>

  <style type="text/css">
    h1 {
      font-size: 35px;
      color: darkblue;
      font-family: Helvetica;
      border-bottom-width: 3px;
      border-bottom-style: dashed;
      border-bottom-color: black;
    }
    
    h2 {
      font-size: 20px;
      color: darkred;
      font-family: Helvetica;
      margin-left: 900px;
      margin-top: -40px; 
      margin-bottom: 70px
    }

    h3 {
      font-size: 13px;
      color: red;
      font-weight: bold;
    }

    .label {
      font-size: 20px;
      color: darkgrey;
      font-family: sans-serif;
      border-bottom-width: 3px;
      border-bottom-style: dashed;
      border-bottom-color: black;
    }

    body {
      background: linear-gradient(white, #a6a6a6);
    }

    .legend {
      font-family: sans-serif;
      font-size: 17px; 
      font-weight: normal; 

    }   


Please ignore the wide formatting, it's optimized for a large touch screen display.

My query pertains to enabling the functionality where clicking on a circle in the legend results in highlighting bars of the same color (specifically the stroke) on the graph.

Many thanks in advance!

Answer №1

Choosing the appropriate bars can be a bit tricky at the moment, as the colors of the bars are not tied to any specific data but rather assigned based on an index:

.attr("fill", function(d, i) {
        return color[i%8] 
      })

If the colors were linked to the data (which is generally a better practice), it would simply involve assigning a class and then highlighting them using that class.

However, there is a method to select all bars with the same color as a clicked circle: by initially selecting all bars and then filtering the selection based on attributes:

.on("click", function(){
            var rects = d3.selectAll("rect").filter(function(){
            return this.attributes.fill.nodeValue == "#1F45FC";
            });
 }); 

You can view the demo here: https://jsfiddle.net/gerardofurtado/z3y0fk74/ (SO snippet wasn't used due to long bars)

Click on the circle, and bars with the same color will have a black stroke (2px width). Click again to remove the stroke.

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

Unlock the power of Javascript in Wordpress by converting a string into a dynamic Page Title

Imagine having a custom-coded menu of links that needs to be added to multiple Wordpress pages. The menu is consistent across all pages, except for the variable part of the link text enclosed in square brackets. Here is how the HTML structure looks: <l ...

Using AJAX to assign PHP session variables

Is there a way to update the SESSION variable named "fullname" on Page 2 without causing the page to refresh? This is my attempt using AJAX: HTML code for Page 1: <input type="text" name="fullname" id="fullname" placeholder="Full name"> <butto ...

Stripping out only the position attribute using jQuery

I have implemented a code with the following characteristics: The navigation items' texts are hidden behind certain Divs, which I refer to as Navigation Divs. When the mouse hovers over these pixels (navigation Divs), the text that is behind the ...

Resolving formatting challenges in R markdown with Blastula

Dealing with formatting problems while trying to include an R markdown file in an email body. As a CSS novice, I'm struggling to find a solution and it's becoming quite frustrating. The table has the following CSS styling: <!DOCTYPE html ...

By setting `queue: false` when calling jQuery's `show()` method, you can

When looking at the code below, it is clear that even though showLoader is the first call, the loader does not appear immediately. This delay is due to the fact that heavyLifting function is blocking the UI thread. function onClick() { showLoader(); ...

Obtaining the "category" and "name" from a stacked bar chart using the Highchart OnClick event

I am working with a Highchart stacked chart that includes a category and dataset structured as shown below: categories =["Clark","Steven","Steve","Robert","Max"] series =[{ name: "Wins" data: [0, 0, 0, 0, 0] }, { name: "Losses" data: [0, 0, 0, 0, 0] }, { ...

using jQuery to retrieve JSON data containing nested arrays

I'm currently working with a music player that requires fetching JSON values dynamically from a page. The issue I am facing is the format of the JSON, which looks something like this: {"audios":[{"audio":{"name":"makakyala","audio":{"audio":{"url":"/ ...

Ways to delay the execution of a loop using setTimeout or setInterval

In my code, I have an array named RotatorNames which includes different elements. Let's say it currently includes ["rotatorA","rotatorB","rotatorC"]. My goal is to loop through this array and trigger a click event for each item. While I have made pro ...

"Discovering the referring page URL in Next.js: A Step-by-Step

On a webpage, I use router.push('destination-url') to redirect users to an external link. I want to determine if the user has navigated back from the redirected page or not. If they arrived from an external link, they should not be allowed to re ...

Having trouble creating a delete button with the $_GET method

My first assignment is to create a script for a webform that allows users to upload files and then displays them in an HTML table on the same page. While my main goal is to get it working, I am struggling with adding a delete button. Here is the code I hav ...

How can I insert <div> elements into arrays in JSX?

I am currently learning React through a tutorial that involves creating a tic-tac-toe game. The tutorial initially renders the game board by hard-coding a list of <div> elements, as shown below: render() { return ( <div> ...

Invoking a prototype method executes the incorrect function repeatedly

I'm currently diving into the world of structures and anonymous functions in JavaScript, and after examining various codes and libraries that implement this technique, I decided to give it a shot. However, when attempting to replicate the method they ...

Is there a universal framework for PHP and JavaScript commands?

Looking for frameworks that handle PHP <=> JS (AKA "AJAX") communication with all the necessary boilerplate code included to make development smoother. Are there any options worth considering? I know there are libraries out there, but most I've ...

Can you explain the distinction between these two forms of functional components in ReactJs?

What sets apart these two code usages? In the FirstExample, focus is lost with every input change (It appears that each change triggers a rerender).. The SecondExample maintains focus and functions as intended. example import React, { useState } from &quo ...

Is it possible to break a single word when word wrapping?

Is it possible to apply word-wrap: break-word to just one word within an element without affecting the entire element? I find that when I apply it to the entire element, it looks messy. I tried searching for a solution but couldn't find anything. Has ...

The height of each Bootstrap column is equal to the height of its corresponding

I am trying to prevent the column height from being equal to the row height in Bootstrap. Here is my code snippet: <div class="row justify-content-center text-center"> <div class="col-sm-3"></div> <div class="col-sm-9"></d ...

I'm looking to showcase the list in a navigation bar by clicking on the hamburger menu. I want to include the 'home' and 'about' text specifically

Having trouble implementing the hamburger menu functionality in my HTML/CSS project. When clicked on a shrunken screen, I want the 'Home' and 'About' text in the nav to appear stacked on top of each other. JS is causing me some difficul ...

Load different fonts dynamically based on environment configuration

My question is regarding loading multiple fonts from a font.css file in React. I need to make the font path dynamic based on the environment variables. Can anyone suggest a solution for achieving this? I've attempted to create a font.scss file and de ...

Press the button to move to the following node

Is there a way to call a function on an image tag's click event without using a specific id, as the image tag has dynamic ids and I cannot directly use 'on-click'? I have tried the jQuery code below but it didn't work. Are there any oth ...

Discover similarities between two arrays

My goal is to compare two arrays and generate a JSON array marking true if there's a match and false if there isn't. The second array will always have values that match some from the first, and it will be smaller as it's derived from the fir ...