Break down the text of a paragraph into separate words, placing each word within its own span element, and then add animations

I am facing an issue with my paragraph element that has the display property set to hidden. I have split each word of the paragraph and placed them inside individual span elements. My goal is to create an effect where each word comes from different locations and sits in the correct order. However, instead of the desired effect, each word is appearing from lower positions to upper positions. How can I achieve the effect I want? Please assist me!

Visit this jsfiddle for reference.

<html>
<head>
<style>
#myp{
display:none;

}
</style>
</head>
<body>
<h3>If you miss the action, please reload the page.</h3>
<p id='myp'>The earth moves round the sun.</p>
<script>
var para;
var para_array=[];
var string;
var splits;
var ids=[];
var m;
var time=10;
k=50;

function init(){

  para=document.getElementById('myp');
  string=para.innerHTML.toString();
  splits=string.split(' ');

  for(i=0;i<splits.length;i++){
    para_array.push(splits[i]);

  }

  for(i=0;i<para_array.length;i++){
    m=document.createElement('span');
    var id='span'+i;
    m.setAttribute('id',id);
    var left=window.innerWidth-(Math.floor(Math.random()*900)+800);
    var top=window.innerHeight-(Math.floor(Math.random()*400)+50);

    ids.push(m.id);
    var style='position:absolute;left:'+left+';top:'+top+';color:red;margin-right:30px;opacity:0;display:block;transition:all 1s ease-in-out;'
    m.setAttribute('style',style);
    m.innerHTML=para_array[i];
    document.body.appendChild(m);
    k+=70;
  }

  var t=setTimeout(function(){
    for(i=0;i<para_array.length;i++){

      var g=document.getElementById('span'+i);
      g.style.top="200px";
      g.style.left=150+time+"px";
      g.style.opacity=1;

      g.style.transform="rotate(360deg)";
      time+=50;
    }
  },100);
}

window.onload=init;
</script>
</body>
</html>

Answer №1

You must remember to include 'px' in your top and left values:

var style='position:absolute;left:'+left+';top:'+top+';color:red;margin-right:30px;opacity:0;display:block;transition:all 1s ease-in-out;'

The corrected version should be:

var style='position:absolute;left:'+left+'px;top:'+top+'px;color:red;margin-right:30px;opacity:0;display:block;transition:all 1s ease-in-out;'

Additionally, it seems you intended to use Math.random instead of Math.round.

Here is the updated code: http://jsfiddle.net/gaurav5430/R92f9/1/

Answer №2

gaurav5430 has already provided a solution to your query. I have taken the liberty to refine the code for you. Additionally, I have made some modifications to your jsfiddle to ensure that the words are evenly spaced.

http://jsfiddle.net/R92f9/2/

var paragraph = document.getElementById('myp');

function initialize(target){
    var words = paragraph.innerHTML.toString().split(' ');
    var spans = [];
    var leftPosition = window.innerWidth - (Math.floor(Math.random() * 900) + 800);
    var topPosition = 1000 - (Math.floor(Math.random() * 10) + 50);
    var style='position:absolute; left:'+leftPosition+'px; top:'+topPosition+'px; color:red; margin-right:30px; opacity:0; display:block; transition:all 1s ease-in-out;';
    var wordSpacing = 10;

    for(var i=0; i<words.length; i++){

        var spanElement = document.createElement('span');

        spanElement.setAttribute('style', style);
        spanElement.innerHTML = words[i];
        document.body.appendChild(spanElement);

        spans.push(spanElement);

    }

    var timeout=setTimeout(function(){

        var currentLeftPosition = 150;

        for(var i=0; i<spans.length; i++){
            var span = spans[i];

            span.style.top       = "200px";
            span.style.left      = currentLeftPosition+"px";
            span.style.opacity   = 1;
            span.style.transform = "rotate(360deg)";

            currentLeftPosition += span.offsetWidth + wordSpacing;

        }

    },1000);
}

window.onload=function(){initialize(paragraph, 10);};

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

This error message in AngularJS indicates that the argument 'fn' is not being recognized as a function

I am currently working with angularjs and typescript and I am attempting to create a directive in the following manner: Below is my controller : export const test1 = { template: require('./app.html'), controller($scope, $http) { ...

scrolling malfunction

I encountered a problem with the scroll feature in this image: The problem is that I only want the vertical scroll to show up, not the horizontal scroll. I tried using the overflow:scroll attribute in my code. Will it display the same in Firefox and IE, o ...

Download personalized HTML design

Situation When exporting to HTML, the resulting code appears as follows: <html> <head> <title></title> <meta content="text/html; charset=UTF-8" http-equiv="Content-Type"> <style type="text/css" ...

Tips for integrating the connect-orientdb module with the Express framework

My objective is to establish a connection between my server code, written in nodejs using the expressjs framework, and my database which is built on orientdb. Initially, I aimed to store sessions in the database but encountered difficulties when trying to ...

"Is there a way to retain the value of a variable outside of an ajax success

I've been working on some form validation functions and here's what I've come up with: <script> $(document).ready(function() { var dataObject = {}; $('#username').keyup(function () { id = $(this).attr('id'); ...

Eliminate an item from a JavaScript array

I am trying to remove a specific element from a JavaScript array. The element I need to remove is the one with the value of 'NT'. In my HTML input, I have: <input type="text" id="caseType" size="50"/> To populate it, I use: var c ...

What is the best way to provide a static file to an individual user while also sharing its file path

I have integrated jsmodeler (https://github.com/kovacsv/JSModeler) into my website to display 3D models. Currently, users can only select a file using a filepicker or by entering the path in the URL (e.g., http://localhost:3000/ModelView#https://cdn.rawgit ...

Trouble with Div Display

I have a section below my form that will show an alert message if there is an error. The issue I am facing is that if I use the inline-block property, everything within the section will be displayed in the alert color. I specifically want the background- ...

What advantages does the Step function (AWS) offer compared to setTimeout (Javascript) for scheduling tasks?

I am currently in the process of developing an API service that allows any client to provide me with their HTTP request along with the desired time in seconds for execution. I have considered two potential approaches to achieve this: Utilizing a lambda f ...

Error in AngularJS - filterProvider not recognized

When the two script statements below are combined, they cause an error: "Error: [$injector:unpr] Unknown provider: searchNameFilterProvider <- searchNameFilter." Can someone explain why this happens? 1st segment Find Person: <input type="text" ng-m ...

The distinction between storing data and component data becomes apparent when using Vuex in conjunction with a persisted state

Below is my post.js file in the store directory: import axios from 'axios' import createPersistedState from "vuex-persistedstate" export default { namespaced: true, state: { sample_data: 'Welcome!!', l ...

How to style the videojs chapter menu with CSS to extend the box to the full length of the line

I am currently working on customizing the videojs CSS for the ChapterButton menu in order to make it expand to accommodate varying line lengths without wrapping. Even though I can set it to a fixed width, I require it to be able to adjust to different line ...

Incorporating a protected Grafana dashboard into a web application

I am looking to incorporate Grafana into my web application using AngularJS. The main objective is to allow users to access the Grafana UI by clicking on a button within my application. Setting up an apache reverse proxy for Grafana and ensuring proper COR ...

What purpose does the "io" cookie serve in Socket.IO?

Can someone explain the purpose of Socket.IO using the io cookie as a session cookie? I understand that it can be disabled, but I couldn't find any information on it in the documentation. Why is it turned on by default and what consequences would ther ...

Utilize new metadata options to incorporate an external style and script file

I'm looking to incorporate external CSS and scripts into my NextJS app (NextJS version 13.4.13). Here's what I need: Style https://company.com/statics/1/package/dist/1/styles/dls.min.css Script https://company.com/statics/1/package/dist/1/ ...

Error: Unable to assign a value to the statusCode property because it

During the development of my application backend, I encountered an error while working on the user login route. When testing the route using Postman, I received the following error message: UnhandledPromiseRejectionWarning: TypeError: Cannot set propert ...

What is the best way to invoke an external JavaScript source using another JavaScript source?

I am trying to connect 2 different files together. file1.php and document.html file1.php has the following code in it: document.writeln('< script src="https://www.googletagservices.com/tag/js/gpt.js"> googletag.pubads().definePassback ...

construct a table utilizing JSON information

If I have data returned from an ajax call that needs to be processed, a table like the following needs to be created: ID NAME Object Type ============================================== 1 SWT-F1-S32-RTR-1 Network Switch 2 ...

What could be causing my bounce animation to begin 50 pixels higher than its intended starting point?

Trying to create a bouncing effect on text Check out my attempt here. It seems like the bug is in this area. @keyframes bounce{ 0%, 40%{ transform:scale(2,.5) translate(0,100px); } 45%,55%{ transform:translate(0,-50px); } 55%, 100%{ ...

able to utilize service within a loop

import { Component, Input, Output, OnInit, OnChanges } from '@angular/core'; import { ViewComponent } from '../view/view.component'; import { HitoService } from '../../services/hito.service'; @Component({ selector: 'ap ...