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

What is the process for creating a beveled edge on a block div?

I am working on an HTML document that includes a DIV tag with specific styling: <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>DIV Tag</title> <style type="text/css"> ...

Eliminate placeholder text when the tab key is pressed

I'm currently facing an issue with a textarea that has a placeholder and the Tab key functionality in Internet Explorer. I've included placeholder.js to make it work, but when I repeatedly press the tab key and focus on the textarea, the placehol ...

The boundary of embedded components

I am looking for CSS code that will allow me to arrange all elements with specific indents, such as placing the first element on the left side of the page, followed by an image with some indentation, and so on. <div class="container-fluid"> &l ...

Tips for creating a clickable textbox

Does anyone know how to make a textbox clickable even when it is set as readonly. I'm looking for a way to make my textboxes clickable like buttons because I have some future plans for them. <input type="text" readonly value="Click me" id="clickm ...

AngularJS flip card animation

Exploring the new AngularJS method for animations during page transitions, I am keen on integrating a card flip effect (resembling http://jsfiddle.net/nicooprat/GDdtS/) body { background: #ccc; } .flip { -webkit-perspective: 800; width: 400px; height: ...

Sit tight as we prepare all static assets for loading on the screen

Currently, I am developing a vuejs application that will incorporate video elements. To enhance user experience, we are interested in preloading these videos upon the initial loading of the web application. I am considering using a listener like, documen ...

The HTML element <p> is not spilling over onto a new line

Having trouble with text overflow in a kanban board? I've tried various CSS styling options like overflow-wrap: break-word;, word-wrap: break-word;, and hyphens: auto;, but nothing seems to work. Here's a preview. I'm using Vue.js, but I do ...

Node.js: Issues with using async await inside a map function

Currently, I am in the process of developing a clone of Tinder. My focus right now is on working on the match/post request within my backend code. This request involves calling a separate function named match, which is triggered after the current user ha ...

Error: Unable to find the specified "location.ejs" view in the views directory

I am encountering the following error - Error: Failed to find view "location.ejs" in views folder "e:\NodeJs_Project\geolocationProject\views" at Function.render Your help in resolving this issue would be greatly appreciated. server.js ...

Having trouble hiding the message "Not found" with ng-hide and filters in AngularJS

I am currently working on incorporating instant search functionality with filters in AngularJS. My goal is to have the "Not Found!!" message displayed when the filter results in an empty array, indicating that no matches were found. However, I have encou ...

Is it possible to create a hyperlink on the second page that directs to the first page and triggers a specific JavaScript function on the first page?

Working with a former colleague's code in C#, asp.net MVC, Telerik/Kendo controls. I am trying to navigate to a specific section on a page from another page that uses tabs/sections with links at the top of the page to toggle visibility based on the se ...

Using jQuery, you can enclose a string of text with HTML tags easily

This specific content within the span is being dynamically created by PHP. However, I am uncertain how to efficiently target the text string in order to begin using jQuery. <!-- input: --> <span class="price">RM1,088.00 Annually + RM10.00 Se ...

Volkswagen elements spilling over

Why are two divs overlapping each other? I have divided the two divs equally with viewport width. When I set the width to 49% instead of 50%, the code works fine. Why is that? <!DOCTYPE html> <html lang="en"> <head> <meta charse ...

Tips for organizing nested form rows with Bootstrap 4

I am currently working on a nested form row and I am looking to align the form fields vertically. The current output I am getting is shown below: https://i.sstatic.net/NEWGY.png Here is the code snippet: <link rel="stylesheet" href="https://maxcdn ...

Button for Autocomplete Component in React Material UI to be displayed after clearing the field

After successfully adding a search button to my Autocomplete Component on Material UI, I encountered an issue where the button always appears before the clear button as shown in this image: I am seeking assistance on how to configure the InputProps so tha ...

Adjusting or cropping strokes in a JavaScript canvas

I am working with a transparent canvas size 200x200. The object is being drawn line by line on this canvas using the solid stroke method (lineTo()). I'm in need of making this object full-width either before or after ctx.stroke();. ...

The Cross-Origin Request has been blocked due to the Same Origin Policy prohibiting access to the remote resource. The reason for this is that the CORS preflight response was unsuccessful

SERVERSIDE // Establishing Headers app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE"); res.header("Access-Control-Allow-Headers ...

Step-by-Step Guide: Unveiling a Particular Modal Post-Submission of Form with

My website has a form inside a modal, and when the form is submitted, I don't want the modal to close. However, I have encountered an issue because my SQL UPDATE statement redirects to the same page after updating the database. This disrupts the funct ...

Instructions on removing an HTML element from a div that has the attribute contentEditable

Here is an example of HTML code: <div id="editable" contentEditable="true"> <span contentEditable="false">Text to remove</span> </div> I want to be able to delete the entire span element (along with its text) with just one bac ...

Internet Explorer fails to accurately determine the height of a textarea based on the line-height

I need to adjust the display of a textarea to show 4 rows with a line height set to 200%. Take a look at the HTML code: <textarea rows="4" cols="50"> 1 2 3 4</textarea> and the accompanying CSS: textarea { line-height: 2; } It appears ...