Need to fix the problem of loading SVG files one by one and the issue with fading or replacing them

I'm looking to insert svg files into a single div and I've managed to do it successfully on this link:

var div_svg = d3.select("div#example");

svg1 = "https://upload.wikimedia.org/wikipedia/commons/0/02/SVG_logo.svg";
svg2 = "https://upload.wikimedia.org/wikipedia/commons/8/81/Wikimedia-logo.svg";

var createSvg = function(dataset) {
   d3.xml(dataset)
   .mimeType("image/svg+xml")
   .get(function(error, xml) {
      if (error) throw error;
      div_svg.node().append(xml.documentElement);
   });
}

update = function(dataset) {
    div_svg.select('svg')
      .style("opacity", 1)
      .transition()
      .duration(200)
      .style("opacity", 0)
      .remove();
    createSvg(dataset)
}

createSvg(svg1);
d3.select("#one").on("click", function() { update(svg1); });
d3.select("#two").on("click", function() { update(svg2); });

However, I have encountered some challenges:

  1. When switching to another svg file, the first one fades out but the new one stacks below until the previous one completely disappears. How can I smoothly replace one svg with another?

  2. If I rapidly click the svg "button", multiple graphs appear in the div. I could implement a quick fix by checking if the svg has already been rendered, but I'm seeking a better solution to address this asynchronous update issue.

Appreciate your help!

Answer №1

In my approach, I suggest waiting until the SVG has finished loading before initiating the transition that will fade out the previous SVG. Once the transition is complete, remove the old SVG, add the new one, and then fade it in smoothly:

var loadAndTransitionSvg = function(dataset) {
    d3.xml(dataset)
            .mimeType("image/svg+xml")
            .get(function(error, xml) {
                d3.select("#example")
                        .select('svg')
                        .style("opacity", 1)
                        .transition()
                        .duration(200)
                        .style("opacity", 0);

                setTimeout(function(){
                    d3.select("#example")
                            .select('svg').remove();

                    div_svg.node().append(xml.documentElement);

                    d3.select("#example")
                            .selectAll('svg').select('svg')
                            .style("opacity", 0)
                            .transition()
                            .duration(200)
                            .style("opacity", 1);
                }, 200);

                if (error) throw error;
            });
};

updateSvg = function(dataset) {
    loadAndTransitionSvg(dataset)
};

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

Turn off transparency for the child element if the parent element has transparency

In my design setup, there is a container with an opacity set at 0.8. This allows the background image to subtly shine through the content area. The challenge arises when I place a client photo inside this container. The issue is that the photo's opac ...

CSS trick for stylish arrow placement on top of a slide

Hey there! This is my first time navigating through the slick carousel functionality. I'm currently facing a challenge with adjusting the positioning of the arrow within the slider. My goal is to have the arrow displayed at the top level just like the ...

Send FormData as JSON object array using ReactStrap Form and Express server

Currently in the process of learning the MERN stack, I find myself navigating through React and Express for the first time. One of my tasks involves utilizing an API that I had previously set up to update JSON data using React. To accomplish this, I' ...

Having trouble with Material-UI Textfield losing focus after re-rendering? Need a solution?

I am currently utilizing Material-ui Textfield to display a repeatable array object: const [sections, setSections] = useState([ { Title: "Introduction", Text: "" }, { Title: "Relationship", ...

What is the best way to resize a primefaces inputTextArea to match the length of the

I am currently working on improving the appearance of <p:inputTextArea/>. When the page loads, I notice: And when I click on that TextArea: Here is the code: <p:inputTextarea rows="6" value="#{bean.object.value}" style="width: 100%;" /> Is ...

TS1057: It is required that an async function or method has a return type that can be awaited

There was a recent Github issue reported on March 28th regarding async arrow functions generating faulty code when targeting ES5, resulting in the error message: TS1057: An async function or method must have a valid awaitable return type You can find t ...

JavaScript - Modifying repeating numbers in an array

I have a list of numbers that repeats multiple times like this; numbers = [2,3,1,2,1,3,3,1,2] My goal is to increase each repeated number by 10 every time it appears. Therefore, the updated list should look like this; updated_numbers = [2,3,1,12,11,13,23, ...

Utilizing the Calc() method within CSS specifically for adjusting the padding on the left and top sides

I am currently working on a website using HTML and SASS. My design includes a fixed header and aside sections. header{ width: 100%; box-shadow: 0 0 4px rgba(0,0,0,.25); position: fixed; z-index: 5; top: 0; ...

Maintain the aspect ratio of DIV or image

I am looking to maintain the aspect ratio of a DIV element, similar to how it's done on Google Maps. <div id="map" style="background-color: grey;width:100%;"> Map here </div> The current setup adjusts the width based on the window size o ...

Submitting forms using Ajax within a modal pop-up box

Here's an interesting issue that I'm facing: On a test page, when the user clicks to view results, a modal box opens with 3 select boxes. Select Box 1 populates Select Box 2, which then populates Select Box 3 The Problem: After clicking submi ...

What is the best method for implementing page transitions between components in NextJS?

My goal is to create a form that smoothly slides to the right, similar to the one seen on DigitalOcean's website when you click "Sign up using email" here: . While the transition itself is relatively simple, I noticed that DigitalOcean uses 2 separat ...

Updating state array within reducer leads to duplicate execution of calculations

const updateCartReducer = (state, action)=>{ console.log('running the updater function') const existingItemIndex = state.items.findIndex( (item) => item.restaurant === action.item.restaurant && ...

Are there any issues arising from conflicting jQueries?

Hello, I am trying to implement EasyUI GridView and Tab in Asp.net MVC4 by placing two Grids inside a Tab. However, I am facing an issue with this setup. I have included the necessary Scripts and CSS in My Layout: <link href="@Url.Content("~/Conten ...

Breaking down a div with jQuery - tips and tricks!

I have a question regarding jQuery. Consider the following structure: <div class="page"> <p>Lorem ipsum....</p> <p>Lorem ipsum....</p> ... </div> I want to transform it into this format: <div class="pa ...

Designing an image transformation page by segmenting the image into fragments

Does anyone have insight into the creation process of websites like this one? Are there any plugins or tools that can assist in building something similar? ...

Tips on capturing the response data in UI testing automation

Currently, I am working on automating a login page using WebDriverIO for UI Automation. After clicking the Login button, a request to *.com/user/login is triggered in the background. I need to capture this call's response in order to obtain a token r ...

Steps for eliminating a column from a table

By including the detailPanel option, a new column with an icon button will be automatically added. https://i.sstatic.net/RoNue.png Is there a way to eliminate this additional column that is generated? Appreciate your help! ...

Looping through a Vue Bootstrap modal using a v-for directive

I am working on a Vue Bootstrap modal placed within a v-for loop. I need to replace the '1' in both 'v-b-modal.modal-1' and 'modal-1' with the index value, which I can access as {{ index }} while looping through the items. How ...

Utilizing Vue libraries within Django templates: A step-by-step guide

For my current project, I'm incorporating Django templates and integrating Vue as a script: <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> My next step is to utilize various Vue libraries that can be installed via n ...

Trouble with Basic JavaScript Comparison Function

I'm facing an issue with a JavaScript comparison that doesn't seem to be working. It's puzzling why it's skipping to line 12302 and setting showNoDataText = true. The logic dictates that it should be false since the array length of 285 ...