Restoring styles back to the default CSS settings

I am currently working on creating visualizations using D3, and one challenge that I have encountered is the need to define a lot of styles within my code instead of in my CSS where I would prefer them to be.

This necessity arises mainly to support transitions. I have observed that while it is possible to transition from a CSS-applied style to an inline one, reverting back to the original style becomes problematic. In order for transitions to work smoothly, all styles must be defined inline as demonstrated in the following example:

var svg = d3.select("svg");

var c1 = svg.append("circle")
            .attr("class", "red")
            .attr("r", 25)
            .attr("cx", 50)
            .attr("cy", 50);

var c2 = svg.append("circle")
            .attr("r", 25)
            .attr("cx", 250)
            .attr("cy", 50)
            .style("fill", "red");

svg.selectAll("circle")
   .transition()
   .delay(2000)
   .duration(2000)
   .style("fill", "blue");

c1.transition()
  .delay(5000)
  .duration(2000)
  .style("fill", "");

c2.transition()
  .delay(5000)
  .duration(2000)
  .style("fill", "red");
.red { 
   fill: red;  
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<svg width="500" height="500">
</svg>

The circle on the left abruptly changes back to red without transitioning, whereas the one on the right smoothly transitions back.

I am looking for a more elegant solution to transition the left circle back without needing to redefine the original color from CSS within my JavaScript code.

If anyone has any insights or suggestions on how this can be achieved gracefully, I would greatly appreciate it!

Answer №1

After following Gilsha's advice, I uncovered a workaround where I can access the original CSS style later on without saving it. Even if the color is initially blue, I am able to revert back and retrieve the red color:

c1.transition()
  .delay(5000)
  .duration(2000)
  .style("fill", function(d) { 
       var selection = d3.select(this);
       var currentStyle = selection.style("fill");
       var defaultStyle = selection.style("fill", null).style("fill");
       selection.style("fill", currentStyle");
       return defaultStyle;
 });

var svg = d3.select("svg");

var c1 = svg.append("circle")
            .attr("class", "red")
            .attr("r", 25)
            .attr("cx", 50)
            .attr("cy", 50);

var c2 = svg.append("circle")
            .attr("r", 25)
            .attr("cx", 250)
            .attr("cy", 50)
            .style("fill", "red");

svg.selectAll("circle")
   .transition()
   .delay(2000)
   .duration(2000)
   .style("fill", "blue");

c1.transition()
  .delay(5000)
  .duration(2000)
  .style("fill", function(d) {
       var selection = d3.select(this);
       var currentStyle = selection.style("fill");
       var defaultStyle = selection.style("fill", null).style("fill");
       selection.style("fill", currentStyle);
       return defaultStyle;
  });

c2.transition()
  .delay(5000)
  .duration(2000)
  .style("fill", "red");
.red { 
   fill: red;  
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<svg width="500" height="500">
</svg>

Answer №2

Give this code a shot.

let backgroundColor = el.style("background-color");

const svgContainer = d3.select("svg");

const element1 = svgContainer.append("circle")
            .attr("class", "blue")
            .attr("r", 30)
            .attr("cx", 70)
            .attr("cy", 70);

const element2 = svgContainer.append("circle")
            .attr("r", 30)
            .attr("cx", 270)
            .attr("cy", 70)
            .style("fill", "green");

//Retrieve background color from CSS
let backgroundColor = element1.style("fill");

svgContainer.selectAll("circle")
   .transition()
   .delay(3000)
   .duration(2000)
   .style("fill","yellow");

element1.transition()
  .delay(6000)
  .duration(2000)
  .style("fill", backgroundColor);

element2.transition()
  .delay(6000)
  .duration(2000)
  .style("fill", "green");
.blue {
   fill: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<svg width="600" height="600">
</svg>

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

Learn how to apply inline styles to multiple objects within a single element using React

In my project using React, I am attempting to apply styles only to a specific element within another element. Here is an example with an h1 tag: const Header = () => { const firstName = "Ashraf"; const lastName = "Fathi"; const date = new Date() ...

How is it possible that this component is able to work with slotting without needing to specify the slot name

I have created two Web Components using Stencil.js: a Dropdown and a Card. Within my Dropdown, the structure is as follows: <div class='dropdown'> <slot name="button"/> <slot/> </div> The nested chil ...

Moving the final item in the list to the end

I've chosen to implement the Vali Admin theme and am currently attempting to move the last list item in the left sidebar to the bottom. While I have limited experience with flexbox, I decided to change the menu to display: flex and followed the steps ...

I am experiencing issues with the customsort function when trying to sort a column of

Seeking assistance with customizing the sorting function for a Date column in a primeng table. Currently, the column is displaying data formatted as 'hh:mm a' and not sorting correctly (e.g. sorting as 1am, 1pm, 10am, 10pm instead of in chronolog ...

Encountering the error message "require is not defined" in the browser while utilizing gulp-browserify for my React.js modules

I am currently working on using gulp-browserify for creating a bundle.js file that will be utilized in the client's browser to initiate rendering of React components. Below is my App.js file: /** @jsx React.DOM */ var React = require('react&apo ...

Occasions focused on the <input type="file"> feature

Looking for a way to write a file input in React that accepts CSV files, validates them, and prevents upload if there are errors? Check out the code snippet below: <CustomInput type="file" id="fileBrowser" name="file" label={filename || 'Choos ...

Phonegap: Displaying audio controls and metadata for my audio stream on the lock screen and in the drop-down status bar

After successfully creating my initial android app for phonegap 5.1 that plays an audio stream, I am currently facing an issue. I am unable to locate any solutions: How can I display audio controls and metadata of my audio stream on the lock screen as well ...

Ways to efficiently handle numerous asynchronous requests in a NodeJS/Express API

I am looking to consolidate a variety of REST APIs into a single, easy-to-use API. My plan is to develop a straightforward nodejs/express API that will handle the individual calls asynchronously and then aggregate all the results together at once. The Jav ...

How can we leverage Shared and Core modules alongside Feature modules in Angular development?

When developing my Angular application, I have adopted a specific architecture approach and included a shared.module.ts file in the shared folder. While leveraging lazy-loading in my app, I find myself puzzled about the necessary imports, declarations, and ...

Tips for assigning a class to an Angular accordion header when the panel is in the open state

I am currently utilizing the Angular UI Bootstrap accordion feature, which can be found here. <div ng-controller="AccordionDemoCtrl"> <div accordion close-others="oneAtATime"> <div accordion-group heading ...

How do I redirect with a GET method after calling the *delete* method in Node / Express server?

As someone new to AJAX and Node, I encountered a dilemma that I hope to get some guidance on. Here's the issue: I have a DELETE ajax call that removes a row from the database and I want to redirect back to the same route with a GET method afterwards. ...

Manipulating background scrolling using jQuery

I had a vision of creating a logo with PNG transparency and a scrolling background that would give the appearance of being made in Flash. To achieve this effect, I utilized the jquery.backgroundPosition.js plugin for enabling background scrolling. Here is ...

Steps for styling an AngularJS Popup:1. Determine the desired appearance for

I have some code that displays a popup when clicked, along with its automatically generated CSS. I want to be able to make changes to the CSS by adding IDs or classes to it. How can I assign IDs or classes to this element so that I can easily target them f ...

Executing a Callback in Node with Redis Publish/Subscribe

Is it possible to implement callback with the PubSub design pattern in Node Redis? For example: server.publish("someChanel", someData, function(response) { // Expecting a response from client }); client.on('message', function(channel, data, ...

What is the process for obtaining the cypress interception fixture twice but in two distinct formats?

Hi there, I'm new to Cypress and facing a challenge that I hope you can help me with. In my test file, I have the following code: cy.SetupClassificationsStubFixture(1); This code refers to a custom command that I've created: Cypress.Commands.ad ...

Creating a scrollable nested div on a mobile website

Is there a way to achieve a scrollable nested div on a jQuery mobile site? I am aiming for a fixed header and footer with the middle section being scrollable. Despite my attempts to set overflow:scroll (along with specifying the width and height of the div ...

Having trouble with making a POST request in Node.js using Express.js and Body-parser?

Just starting out with nodejs and currently in the learning phase. I've encountered an issue where my POST request is not functioning as expected. I set up a basic html form to practice using both GET and POST requests. Surprisingly, the GET request w ...

Get rid of all numbers from a jQuery selection except for the first and last

I am dealing with an array let numberArray = ["500", "600", "700", "800", "900", "1000", "1100", "1200"] My objective is to remove all elements except for the first and last ones. The challenge arises when the array contains only one value, as I must ens ...

Stop the background from scrolling and prevent auto-jumping to the top on mobile devices

When users click on the hamburger icon in the top right of our mobile site, I want the drop-down menu to appear and be scrollable without the background scrolling. I tried using JavaScript to set the body to fixed when the menu icon is clicked, but this ca ...

The best approach to incorporating interactive animation in next.js

My vision is to develop a character creation application using next js. The app should empower users to customize the character using sliders and gender selection buttons. The ultimate goal is to have a 2D animated version of the character that dynamicall ...