Adjust the shading of an SVG element with every button click by utilizing either D3 V3 or JavaScript

I am working with a D3 graph that includes Nodes/Links. I have implemented a feature where clicking on a node and then a button will decrease the opacity of all other elements except for the interconnected nodes and links, changing them to blue to indicate a circuit.

https://i.sstatic.net/zDcKb.png

My goal is to have the common links in multiple selected circuits change to a slightly darker shade of blue.

Instead of adjusting the opacity, I want to achieve this effect by darkening the color tone each time.

I have the logic to identify common links within a circuit using D3/JS. How can I incrementally darken the color of an SVG element on button click?

For instance, in the code snippet provided below, I aim to progressively darken the blue color instead of switching it to red upon button click.

d3.select('#toDO').on('click', function() {
d3.select("#PathID").attr("stroke" , "red")
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<svg height="210" width="400">
  <path id="PathID" d="M150 0 L75 200" stroke="blue"/>
</svg>
<button id="toDO">Click</button>

Answer №1

When working with D3, there is a useful method called darker(k), which does exactly what the name suggests:

This method returns a darker version of the given color. You can specify the darkness level by providing the 'k' parameter. If no value is provided, it defaults to 1. The outcome of this function depends on the color space being used.

To achieve this in your code using D3 v4 or v5, you simply need to utilize d3.color:

d3.color(d3.select("#PathID").attr("stroke")).darker()

Alternatively, for D3 v3, you can use d3.rgb:

d3.rgb(d3.select("#PathID").attr("stroke")).darker()

Here is a demonstration of how this works:

d3.select('#toDO').on('click', function() {
  d3.select("#PathID").attr("stroke", d3.rgb(d3.select("#PathID").attr("stroke")).darker())
})
<script src="https://d3js.org/d3.v3.min.js"></script>
<button id="toDO">Click</button>
<br>
<svg height="210" width="400">
  <path id="PathID" d="M150 0 L75 200" stroke="blue" stroke-width="10px"/>
</svg>

If you click the button multiple times in the demo, you will notice the stroke color getting progressively closer to black.

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

Tips for storing dynamically added row data from an HTML table to a (csv/txt) file using C#

I am dynamically adding new rows to a table named "newDataTable" using the JavaScript function below: function addRow() { //add a row to the rows collection and get a reference to the newly added row var table = document.getElemen ...

Error: Module not found - Imported Node Module

I have been struggling to make modifications to an npm package with little success. I have spent hours troubleshooting and would greatly appreciate some guidance. https://www.npmjs.com/package/dxf After forking the package into my Github account, I proce ...

Unveiling the method to retrieve AuthErrorCode from Firebase JS SDK without the need for the auth/ prefix

I'm curious about how to retrieve the correct error code in Firebase v10. public resetPassword(email: string, actionCodeSettings: ActionCodeSettings): Promise<void> { return sendPasswordResetEmail(this.auth, email, actionCodeSettings); } publ ...

Switching the background hue of the chat box after each message

Does anyone know how to change the colors of each message in a chat window using CSS and HTML? I'm trying to customize my stream but can't figure it out. Here is an example for reference. ...

Removing message board posts

In my database table, I have fields called wall_posts, group_id, id, and user_id. Wall_posts store user entries, group_id is a unique identifier imported from another table, id is a simple counter, and user_id holds the user id retrieved from the session. ...

Arranging text within a td cell

This is what I currently have: <tr> <td colspan="4" style="font-size:7pt; font-color:red; font-weight: bold;"> PLEASE NOTE: SPECIFY THE ARTICLE IN AS MUCH DETAIL AS POSSIBLE </td> </tr> However, the text does not a ...

"An issue arises where the bokeh plot fails to render when generating a

I have been working on embedding a bokeh plot within a webpage served by a simple Flask app. I am using the embed.autoload_server function that I found in the bokeh embed examples on github. While everything seems to be functioning correctly on the Python ...

Exclusive Hover Effect: Applying Hover Styles Only to Child Elements, Independent from Parent Hover

Styling with components is a great way to enhance your web design. const box = style.div` background-color: blue height: 300px ` const image = style.img` filter: grayscale(50%) ` <box> <image /> </box> If <image> stands alo ...

Applying media queries to a <div> instead of the entire viewport can be a useful technique, especially when used in conjunction with

I am looking to create a dynamic layout where different content such as tables and masks can be displayed in multiple areas or columns on a website. Typically, the left column will contain a list, the middle column details of an entry, and the right column ...

Are you accessing the site on a variety of gadgets?

I am currently working on a website with the goal of making it responsive. So far, it looks great on desktops and mobile phones like the iPhone and Galaxy S4. However, I am encountering difficulties in making the website look like it is on a mobile phone w ...

The program encountered an issue where it was unable to access the 'email' property due to its null value

While implementing form validation for email in my Angular 5 template driven form, I encountered the following error - ERROR TypeError: Cannot read property 'email' of null. Below is the snippet of HTML code containing the form structure: < ...

Creating a bump chart using structured data: A step-by-step guide

The bump chart example provided by ECharts includes sections with randomly generated data, which can be confusing for those unfamiliar with JavaScript or TypeScript. What would the code appear like if it didn't rely on data generation? ...

Using the && operator for conditional rendering in a React return statement

How should I format my return statement in a class component when using the && operator in the condition like this: if (x === null && y === null) If the condition is met, display this HTML: <div className="col-12"> <SomeComponent /> < ...

The ng-route feature seems to be malfunctioning and I am unable to identify the error, as no information is being displayed in the console

Here is the code in my boot.php file where I have set up the links <ul class="nav nav-pills nav-stacked"> <li role="presentation"><a href="#/valley">Valley</a></li> <li role="presentation"><a href="#/beach"> ...

What is the best way to incorporate a custom margin within a grid system while ensuring it remains responsive?

I'm currently working on incorporating 4 non-bootstrap "cards" into my HTML layout, with some space between them. Here is an image depicting how it's supposed to look: https://i.sstatic.net/bppvW.png The problem arises when I attempt to make the ...

URL for CSS Background-Image

While working on CSS styling for the body, I ran into a problem and was curious to understand the distinction. Initially, I tried this body { background-image: url('img/bg.png'); } However, it did not produce the desired result. http://www ...

Explore the wonders of our solar system using three.js!

I am embarking on my first project using three.js to create a miniature solar system consisting of 1 star, 2 planets, and 1 moon orbiting each planet. As a beginner to both three.js and JavaScript in general, I am eager to learn. Currently, I have success ...

Extract image styles from a different webpage

My website is located at: I'm attempting to replicate the testimonial photo effect that can be seen on this website: https://i.sstatic.net/70Jqd.png What CSS code do I need to include in order to make the image with the class "client-pic" circula ...

Taking pictures with the camera in three.js on an iPhone

While working on a project that required capturing the camera video stream as a texture in three.js for mobile phones, I encountered an issue. The code I was using ran smoothly on Android devices but not on iPhones. Ideally, when the user grants permission ...

A method for applying the "active" class to the parent element when a child button is clicked, and toggling the "active" class if the button is clicked again

This code is functioning properly with just one small request I have. HTML: <div class="item" ng-repeat="cell in [0,1,2]" data-ng-class="{active:index=='{{$index}}'}"> <button data-ng-click="activate('{{$index}}')">Act ...