Guide to smoothly transitioning a collection of heterogeneous foreign elements within varying time intervals using D3

I am currently experimenting with transitioning opacities of a group of foreignObject text. My goal is to have each element transition individually at random durations, rather than all at the same time. Is it possible to achieve this without creating separate variables for each one? Thank you for looking into this.

        var city = canvas.append('g')
                    .attr('width',1024)
                    .attr('text-anchor','start');

        city.append('foreignObject')
            .attr('x',40)
            .attr('y',0)
            .append('xhtml:body')
            .html("<h1>Milwaukee</h1><p>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p>");

        city.append('foreignObject')
            .attr('x',365)
            .attr('y',0)
            .append('xhtml:body')
            .html("<h1>Chicago</h1><p>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p>");

        city.append('foreignObject')
            .attr('x',690)
            .attr('y',0)
            .append('xhtml:body')
            .html("<h1>Detroit</h1><p>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p>");
        
        // Additional foreignObject elements
        
        city.transition()
            .duration((Math.random() * 500) + 100)
            .delay(0)
            .attr('opacity',0)
            .transition()
            .duration((Math.random() * 500) + 100)
            .delay(Math.random() * 500)
            .attr('opacity',1);

Answer №1

At this moment, the city exists as a single entity. This means that the opacity changes are being applied to that specific group only.

An alternative approach is to target all foreignObjects using an each loop:

canvas.selectAll("foreignObject").each(function() {
    d3.select(this).transition()
        .duration((Math.random() * 1000) + 1000)
        .style('opacity', 0)
        .transition()
        .duration((Math.random() * 1000) + 100)
        .delay(Math.random() * 500)
        .style('opacity', 1);
})

Check out this demonstration:

var canvas = d3.select("body")
  .append("svg")
  .attr("width", 800)
  .attr("height", 600)

var city = canvas.append('g');

// Code for adding foreignObjects...

canvas.selectAll("foreignObject").each(function() {
  // Code for transitioning opacity...
})
<script src="https://d3js.org/d3.v4.min.js"></script>

Note: Make sure to specify the width and height of the foreignObjects.

Additional note: When altering the opacity of foreignObjects like you're currently doing, there may be some issues. This response specifically addresses your question and not those potential bugs. The outcome presented above might exhibit some flaws.

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

Steps for successfully sending data to a MenuItem event handlerExplanation on how to

My issue arises when I attempt to render a Menu for each element in an array, as the click handlers for the items only receive the final element in the array rather than the specific element used for that particular render. The scenario involves having a ...

What is the best way to incorporate the final paragraph into the foundational code?

I'm attempting to create my own version of the lyrics for 99 Bottles of Beer Here is how I've modified the last line: 1 bottle of beer on the wall, 1 bottle of beer. Take it down and pass it around, no more bottle of beer on the wall. How ...

Offspring maintain a certain position within the larger framework of their parent on a

When resizing the parent wrap container, how can I ensure that the pin (red dot) on the image maintains its relative position? To see the issue, resize the wrap container. #wrap{ position: absolute; width: 100%; height: 100%; top: 0; l ...

What is the best approach for connecting Advanced Custom Fields in WordPress to components in my Next.js frontend using GraphQL?

Currently, I am in the process of constructing a website by utilizing WordPress as the headless CMS and NextJs for my frontend. My dilemma lies in using the free version of ACF and wanting to dynamically query and map ACF to components in Next when generat ...

Tips for displaying NoOptionsText in MaterialUI Autocomplete based on a specific condition

When using a Material UI autocomplete feature, the items are selected based on the first 3 letters typed. For example, if you're searching for all "Pedros" in your database, typing "Ped" will bring up results starting with those letters. The issue ar ...

Experiencing difficulty retrieving individual :id information from a list in MEAN stack

**I'm experiencing issues retrieving a single :id from a list as the data returned is not what I expected... ** GET /article/5b0be8829f734a4e580a43c5 401 3.845 ms - 99 ===> response from my get request my api ===> var express = require ...

Ways to steer clear of using eval for converting strings to decimal values

I currently have the fraction "1/7" and I am looking to convert it into a decimal. While I know I can achieve this using eval("1/7"), I prefer not to use eval as it is considered harmful. Are there any alternative methods to accomplish this? ...

Adapting the current codebase to be compatible with Typescript

Currently, my codebase is built with redux, redux-saga, and react using plain Javascript. We are now considering incorporating Typescript into the project. Some questions arise: Can plain Javascript files coexist with tsx code? I believe it's possibl ...

Utilizing JavaScript and jQuery to make a query to mySQL

Looking to solve a SQL database query challenge using JavaScript or jQuery? Here's the scenario: I have a SQL db and typically use the following query to retrieve data based on distance from specified coordinates: SELECT id, ( 3959 * acos( cos( rad ...

Experience seamless slide transitions with the react-slick carousel using scroll events in React JS and JavaScript

Currently utilizing the carousel library found at: react-slick I am interested in enabling mouse scroll functionality to navigate through each slide. The idea is to scroll up to progress forward and scroll down to go backward. Came across a relevant exa ...

Monitor website visitors' traffic sources using the Google Analytics Nuxt module

Recently I integrated Google Analytics into my Nuxt website. After installing the module, I configured it in the nuxt.config.js file like this: gtm: { id: 'GTM-WGW****' }, googleAnalytics: { id: 'UA-230******-*' ...

Retrieve the exact value of a key within a string

This is my unique text: let x = "Learning new things every day!"; I am utilizing the substring() method to extract a specific part of it: console.log(x.substring(9, 12)); Instead of the entire string, I only want the word 'new'. let x = "l ...

What is the reason for the regeneration of the 2D array?

I have a method called generateWeights() that retrieves random values in an array; And a method named learn() that calls the changeWeights() method to alter the values in the array. Expected: Prior to invoking the learn() method, I anticipate receiving an ...

Three.js: universal rotation

My goal is to rotate all elements within a scene around the origin point of 0,0,0 specifically along the x-axis. Despite attempting to set obj.rotation.x += 0.1;, I'm facing the issue that instead of rotating around the origin, the object rotates arou ...

What could be causing the slow compilation of my Next.js pages within the app directory, and what steps can be taken to improve the speed of this

Currently, I am working on a Next.js project that uses the 'app' directory structure. However, during local development, I have been facing significant delays in compile times. Here's a breakdown of the compile times I am encountering: - Th ...

Attempting to incorporate icons into a Material UI table design

Hello, I've incorporated a Material UI table into one of my projects with a design concept similar to this - https://i.stack.imgur.com/i6Fsj.png I'm aiming to include icons within the tables. Here's the code I've worked on so far - ...

Converting the source to your image assets in Angular: A step-by-step guide

I am looking to update the source code. Here is an example: <div *ngFor="let item of meal.allergenList" class="btn btn-primary"> <img [src]="item" alt=""> </div> I want to make the following co ...

JavaScript debugging causing system freeze

Currently, I am working on a project that involves using MVC and dropdown lists. My issue arises when the dropdown list changes, as there is some javascript code that needs to execute. To troubleshoot the problem of the system locking up every time I tried ...

Does the ThreeJS Bloom Example provide the desired outcome when copied line by line?

Comparing the results of my bloom filter with an online example reveals some discrepancies. Online Example: https://i.sstatic.net/l7hOtm.png My Output: https://i.sstatic.net/vc7ytm.png Although I have copied the example code exactly, my output does no ...

What is the method for specifying the content type when generating a signed URL for an object in AWS S3?

I am trying to generate a signed URL with a custom content-type, but I am encountering an issue when attempting the following: s3.getSignedUrl('getObject', {Bucket: AWS_BUCKET_NAME, Key: 'myObjectsKey', ContentType: 'image/png&apos ...