Tips for rotating individual letters within a sentence on popular web browsers, including Chrome

Can you make a sentence appear with each individual letter rotating and getting larger?

This is my approach: I decided to split the sentence into separate span elements, one for each letter. Then I used CSS transform -webkit-transform to animate the letters. Unfortunately, this didn't work in Chrome until I added display: inline-block. However, this caused the spaces between words to disappear, making everything run together.

Check out the example below or here

let containerDiv = "div.chart";

function displayText(_textArray) {
  let sel = d3.select(containerDiv);

  // add headers for all strings but the last one
  for (let i = 0; i < _textArray.length - 1; i++) {
    sel.append("div")
        .attr("class", "header h" + i)
      .append("h1")
        .attr("class", "trans")
        .text(_textArray[i]); 
  }

  // add last string by wrapping each letter around a span
  // which can be styled individually
  let sel2 = sel.append("div")
        .attr("class", "header h" + (_textArray.length - 1))
      .append("h1")
        .style("opacity", 1)
        .attr("class", "trans");

  const lastString = _textArray[_textArray.length-1];
  for (let i = 0; i < lastString.length; i++) {
    sel2.append("span")
      .attr("class", "color-" + (i % 5))
      .text(lastString[i]); 
  }
}

function transitionLetters(_selection){
   _selection
        .transition()
        .duration(2000)
        .delay((d,i) => i * 200)
        .style("opacity", 1)
        .style("-webkit-transform", "rotate(-720deg) scale(1)");
}

let myText = ["I like to eat", "ham and eggs"];
displayText(myText);
d3.selectAll("span").call(transitionLetters);
div.header {
  margin: 0 auto;
  text-align: center;
  width: max-content;
}

h1 span {
  opacity: 0;
  display: inline-block;
  -webkit-transform: rotate(-0deg) scale(0.001);
}

.color-0 { color: rgb(255, 0, 171); }
.color-1 { color: rgb(0, 168, 255); }
.color-2 { color: rgb(171, 0, 255); }
.color-3 { color: rgb(255, 171, 0); }
.color-4 { color: rgb(168, 255, 0); }
<script src="https://d3js.org/d3.v4.min.js"></script>
<meta charset="utf-8">
<body>
    <div class="chart"></div>
</body>

Answer №1

Although the spaces are present, they do not appear because a span element does not display content that consists only of white space.

span { /* or you can use a custom class for those spans */
    white-space:pre;
}

Refer to this response for more information:

Answer №2

To maintain the original spacing, consider including the white-space:pre rule to your h1 span selector.

 h1 span {
  opacity: 0;
  display: inline-block;
  -webkit-transform: rotate(-0deg) scale(0.001);
  white-space:pre;
}

This article offers a summary and reference to various solutions for managing white spaces using CSS: how to make space within span show up

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

Creating consistent indentation in HTML code can be achieved without the presence of any unnecessary

When I add indentation to my HTML code, it results in extra whitespace between elements on different lines. <div id="nbcntcnt"> <a href="notset.html" class="nbcntbutton" id="snbb">Overview</a> <a href="notset.html" class="nbcntb ...

Is there a way to display a modal before redirecting to the next page after clicking a submit button in a rails application?

In the scenario where I have two models, Employer and Jobs, consider this situation: an Employer creates an account to post a job and provides their phone number. When they fill out a new job posting and click on the post job button (Submit button), I need ...

Direct user to an external webpage with Vue 3

I created a navigation bar with links to external social media platforms. After clicking on the GitHub link, I encountered some errors and here are the URLs for reference: https://i.sstatic.net/KCh3C.png https://i.sstatic.net/OXQOK.png <template> ...

Exploring the Dynamic Routing Features of Next.js

After diving into Next.js, I found the learning curve to be manageable since React was already familiar territory for me. Currently, my focus is on implementing dynamic routing in my application - Starting with my live/index.js file - (Where I utilize ge ...

Chrome does not support gradient, while Firefox does

When I attempt to utilize the webkit gradient tag specifically for Chrome, it fails to function altogether. On the other hand, when tested on Firefox using background:-moz-linear-gradient(#000, #888);, it operates smoothly. Despite this, applying backgrou ...

Issue with firing Facebook pixel after router.push() in Next.js

Within this code block is FB pixel tracking code <Script id="some-id" strategy="afterInteractive">some fb pixel code</Script> The issue arises when navigating to a page containing the script using router.push(SOME_ROUTE). T ...

Is there a way to switch an element across various pages within Ionic 3?

Is it possible to exchange information between two pages using logic? I have successfully implemented a checklist, but I am unsure how to add a success/error icon next to the Room name on the 'verifyplace.html' page after invoking the goToNextPa ...

Embedding SVG styling directly into the HTML document

When importing svg images with color into Mapbox Studio, they appear as black and white. The troubleshooting website mentions: If your SVG appears black after adding to Mapbox Studio, it may be due to using style properties in tags instead of inline sty ...

Efficiently adjusting the height of a sticky sidebar

I am currently implementing a Bootstrap grid with two divs in a row. I need my reply-container to be fixed (sticky). However, when setting position: fixed; it is affecting the element's width by adding some additional width. With position: sticky, set ...

I have to display a pop-up message box after selecting an option from a dropdown menu that fulfills a set of conditions

I am attempting to display a pop-up message when a selection is made on a dropdown menu that meets specific criteria. The dropdown list is generated from a coldfusion output query. I am relatively new to JavaScript, so I may be missing something in my code ...

Showing a group of users in real-time as they connect using Socket IO

I've been working on setting up a system in Socket IO to create a list of individuals who join a 'party room'. The plan is to lock the party room once all players are present, and then display views to users. However, I've hit a roadblo ...

Honing in on JavaScript Media Queries within React

I have been attempting to incorporate the media query concept from a resource I found here in my React project. However, when testing the code snippet below, I encountered the following error: TypeError: isMobile.addListener is not a function function App ...

Script that was generated dynamically is failing to run

I have a situation where I am adding a script tag, along with other HTML content, to my current document after making an AJAX call. However, the script is not executing as expected. //Function to handle response function(responseText){ document.getEle ...

What is the best way to begin an ordered list from the number 2 instead of 1, while ensuring W3C validity and compatibility with

Is it possible to start an ordered list from 2 instead of 1? I need the solution to be compatible with all browsers, including IE6, and ensure that the HTML and CSS are valid. ...

Ways to maximize your final export value

My data file, named data.ts, contains a large dataset: export data = [ ... // huge data ] The lib.ts file only utilizes a portion of the data: import { data } from './data.ts'; const fitteredData = data.splice(0,2) // only use some of them ...

Dynamic content that adjusts based on a multi-row element

I'm currently designing a webpage layout with a calendar on one side and a series of information-divs on the other. In desktop view, I want the calendar to span three rows like so: CAL DIV1 CAL DIV2 CAL DIV3 Right now, I am achieving this using neste ...

Ensure that the headers of the table are in perfect alignment with the

Is there a way to create a table with fixed row headers so that column headings stay in place while scrolling? I've managed to achieve this, but now the table headers are not aligned properly with the rows below. I've also created a helpful jsfid ...

Tips for transferring data via ajax to rails 3. The jQuery function is ensuring the string is properly handled

I am attempting to achieve the following: $.ajax({ type: "PUT", url: /example, data: {_method: "put", "foo_model[bar_attribute]": value_var } }); It is working as expected, but I need to dynamically construct the part foo_model[bar_attribute]. ...

Ensuring that all checkboxes have been selected

I have 5 checkboxes all with the attribute name set as relative-view. To confirm that all of them are checked, I know how to verify the first and last one: expect(element.find('input[name="relative-view"]').first().prop("checked")).toBe(true); ...

Is there someone who can assist me in transforming this constructor function into a factory function using Javascript?

const createAppError = (message, status) => { return { message, status }; }; This is the equivalent code using factory functions to create an AppError with a message and status. It achieves the same result as the constructor fun ...