It appears that there are no spaces in the H1 HTML tags

As a beginner in HTML, I decided to incorporate some basic animations into my project. Following a tutorial, I was successful in creating simple animations. However, I encountered an issue where the text within my h1 class lacked spacing despite me adding spaces between words. According to the code editor on w3schools, adding spaces within the h1 class should create adequate space between the words.

Link to W3Schools Code Editor

const text = document.querySelector(".hello");
const strText = text.textContent;
const splitText = strText.split(" ");

text.textContent = "";

for (let i = 0; i < splitText.length; i++) {
  text.innerHTML += "<span>" + splitText[i] + "</span>";
}

let char = 0;
let timer = setInterval(onTick, 50);

function onTick() {
  const span = text.querySelectorAll('span')[char];
  span.classList.add('fade');
  char++;
  if (char === splitText.length) {
    complete();
    return;
  }
}

function complete() {
  clearInterval(timer);
  timer = null;
}
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  background: black;
}

h1 {
  color: white;
  font-size: 4rem;
  font-family: sans-serif;
}

span {
  opacity: 0;
  transition: all 1s ease;
  transform: translateY(50px);
  display: inline-block;
}

span.fade {
  opacity: 1;
  color: red;
  transform: translateY(0px);
}
<h1 class="hello">Testing 1 2 3</h1>

Answer №1

When utilizing your code to search for spaces in a string using strText.split(" ");, it results in the loss of these spaces. To remedy this, you can reinsert the spaces when reconstructing the string by including them along with the added spans using either

text.innerHTML += "<span>" + splitText[i] + "</span> ";
or
text.innerHTML += "<span>" + splitText[i] + "</span>&nbsp;";

const text = document.querySelector(".hello");
const strText = text.textContent;
const splitText = strText.split(" ");

text.textContent = "";

for (let i = 0; i < splitText.length; i++) {
  text.innerHTML += "<span>" + splitText[i] + "</span> ";
}

let char = 0;
let timer = setInterval(onTick, 50);

function onTick() {
  const span = text.querySelectorAll('span')[char];
  span.classList.add('fade');
  char++;
  if (char === splitText.length) {
    complete();
    return;
  }
}

function complete() {
  clearInterval(timer);
  timer = null;
}
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  background: black;
}

h1 {
  color: white;
  font-size: 4rem;
  font-family: sans-serif;
}

span {
  opacity: 0;
  transition: all 1s ease;
  transform: translateY(50px);
  display: inline-block;
}

span.fade {
  opacity: 1;
  color: red;
  transform: translateY(0px);
}
<h1 class="hello">Testing 1 2 3</h1>

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

When the input value is changed programmatically, the onchange event does not execute as expected

Having trouble updating the content of my dataTable when using JS script to change the quantity value. Here is a snippet from my code. <h:inputText id="counterFeatures" value="#{myBean.quantity}"> <f:ajax event="change" render="myDataTable" ...

Using axios to make a request from a server to itself

I'm facing an issue where I am attempting to send a request from the server to the same server using axios as a PUT method. Here is an example of what I have tried: await axios({ url: `http://localhost:4000${url}`, method: requestType, ...

Color-changing background effect when tapping inside a contenteditable element

Is there a way to prevent the background of a contenteditable div from flickering gray when touched inside the div? This issue can be observed on iOS Safari or UIWebview object. Check out this HTML demo for an example: You can also view an image demons ...

Retrieving Information from MongoDB Collection with Paginated Results in Universal Sorted Sequence

I'm in the process of working on a project that involves a MongoDB collection called words, which holds a variety of words. My objective is to retrieve these words in a paginated manner while ensuring they are globally sorted in lexicographical order. ...

Unable to locate child after adding element to HTML

I have been attempting to add a child element to my HTML document, and although I can see it in the source code, it doesn't display on the screen as expected. It's quite baffling. Here is the HTML code snippet: <!DOCTYPE html> <html> ...

Unable to implement the hover property for the entire class in CSS

I am struggling to highlight the entire class element on hover. Even though I have specified the button class as a selector, only the background color of the anchor tag is changing when I hover over the button. What could be causing this issue and how can ...

How can one gain access to a specifically generated element?

In my task of dynamically generating multiple elements, I am facing an issue related to accessing specific ones. To illustrate this problem as simply as possible, I have provided the following code: $(document).ready(function() { var num1 = 0; v ...

Utilize the dropdown menu across all table cells in a table

My p-table has a unique feature - the last column contains three dots that trigger a dropdown menu when clicked. The only issue is that the fixed position of the dropdown menu does not align properly with the td element in each row. Check out the HTML cod ...

Understanding the asynchronous behavior of Mongoose's findById method

I want to discuss the code I am currently working on: const checkForRecord = async (id) => { let model = mongoose.model('User'); let query = {} query.dummy = false; <== This particular field is causing an error intentionally, ...

Triggering a click event on various instances of a similar element type using the onclick function

Hey there, I'm a newcomer to Javascript. I've been practicing my Javascript skills and trying to replicate something similar to what was achieved in this example: Change Button color onClick My goal is to have this functionality work for multip ...

Looking for a way to align HTML and CSS elements effectively

I am facing a challenge with my current code structure. Whenever I try to integrate a fixed solution for one problem, it causes a break in another part of the system. This leads me to believe that there may be some fundamental errors in my approach. Theref ...

Fill the angular ui-bootstrap popover with content

Can anyone help me with populating an angular ui bootstrap popover? My goal is to populate the popover with a collection of actor names. Below is the code snippet: <div class="container" ng-if="radioModel=='Search for Actor'"> <p> ...

Interactive tool for crafting dynamic web experiences

I am in the process of developing a straightforward hosting website for my projects. However, I have noticed that many software options feature a split view for editing code and previewing changes, such as Dreamweaver. I am on the lookout for a live edito ...

Invoking a synchronous JavaScript request to an MVC 4 Controller function

For the code I'm working on, I need certain functions to be executed sequentially. I attempted to use ajax calls but ran into issues due to their asynchronous nature. function GetLibraryActivities(libraryName, callback) { $.ajax({ dataTyp ...

Exclusive Functionality: Bootstrap Drop Down Navigation in ASP.NET Only Functions on Main Pages

I am in the process of developing an internal application with ASP.NET 4.0 using the Yeti Bootstrap Theme. One issue I am encountering is with the navbar dropdown navigation. Pages that are located in the website's root can utilize the dropdown featu ...

Unable to access a JavaScript array in one file from another file in JavaScript

I am having trouble referencing the arrays I created in a.js and then using them in b.js. The arrays are declared inside a.js $(document).ready(function () { categoryarray = []; productarray = []; In my HTML file, I have the following script tags: < ...

Inquire about understanding Mean.js through form submission

Hey there, I'm looking to create a search engine for an application using JS MEAN. I have a database with various elements and I want users to fill out a form to see the results in a separate view. I haven't had much luck so far, I've don ...

How to Properly Align Pagination in a Bootstrap 4 Column

I am currently using Bootstrap 4 and trying to center a pagination UL horizontally inside a grid column. Since the pagination is now displayed using flex, I am facing difficulties in getting it properly centered. I aim to achieve this without adding any e ...

struggling with typing an object in react typescript - Element is assumed to have an 'any' type due to its type

Having trouble with the code snippet below: // if I remove the `any` below it breaks. const teams: any = { liverpool: <Liverpool />, manUtd: <ManUtd />, arsenal: <Arsenal />, }; export const TeamCrest = ({ team }: { team: ke ...

Error: You cannot implement an import statement beyond a module while utilizing reactjs CDN Links

I am developing a Reactjs app using react CDN Links instead of 'npx create-react-app'. I have set up an index.html, index.js, and App.js files. My goal is to import the App.js component into the Index.js file using import App from '../compon ...