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

"Achieving Alignment: Placing a Div Element Inside an H

I am in the process of building a portfolio for freecodecamp, but I am having trouble with centering the button and row div on the page. The row div is necessary because I will be adding more buttons later on, but for now I just need the FCC button. Below ...

Trigger a JavaScript function when a key is pressed down

Hey everyone, I'm trying to figure out how to trigger a JavaScript function when a particular key is pressed. For example, I want the function down() to be executed when the down key is pressed and function left() when the left key is pressed. Is ther ...

JS backbone require global models in js

I am looking to implement a UserSession model that will handle loading and saving session IDs into cookies using the jQuery cookie plugin. Below is the code for my UserSession model module: define(['jQuery', 'Underscore', 'Backbo ...

What is the best way to superimpose text on a variety of images with varying sizes using CSS

I have a client who is requesting a sold text to be displayed on top of all images that have been sold, positioned in the bottom left corner of each image. While I have successfully implemented this feature, the issue arises when dealing with images of var ...

The SVG format quickly displays new and larger datasets on line charts without any transition effects

My goal is to create a line chart with animated transitions similar to this demo, but without the dots. I am attempting to integrate this functionality into a react component where the update method can be triggered by another component, allowing the d3 op ...

The error message "node Unable to iterate over property 'forEach' because it is undefined" appeared

I am facing an error and unable to find the solution. I believe my code is correct. It is related to a video lesson where I attempt to display popular photos from Instagram using the Instagram API. However, when I try to execute it, I encounter this issue. ...

Adding a Timepicker to a Datepicker on a jsp webpage with javascript

I am working on a JSP page that includes a date picker. I want to enhance this datepicker by adding a start time and end time within the calendar itself. How can I achieve this? Additionally, I need to implement validation ensuring that the start time is a ...

Rearrange divs from left to right on mobile display

I need help creating a header bar with three elements as shown below https://i.sstatic.net/4njuk.png When viewed on mobile, I want the menu (toggle-icon) to shift left and the logo to be centered. I attempted using push and pull with no success. Is there ...

The CSS transition will only activate when coupled with a `setTimeout` function

After using JavaScript to adjust the opacity of an element from 0 to 1, I expected it to instantly disappear and then slowly fade back in. However, nothing seems to happen as anticipated. Interestingly, if I insert a setTimeout function before applying th ...

Finding the correct closing tag in HTML can be accomplished using an algorithm

Currently working on my custom HTML parser in JAVA and have completed the lexer. Now diving into coding the parser to create a DOM tree and ensure the proper construction of my HTML. For example, understanding that an img tag is considered a void tag as p ...

No output is displayed in the absence of errors. The program is functioning correctly

app.js angular.module('app', ['ionic', 'ui.router']) .config(('$urlRouterProvider', '$stateProvider', function($urlRouterProvider,$stateProvider){ $urlRouterProvider.otherwise('/'); $sta ...

Guide to organizing files with custom directory layout in NodeJS

Imagine having multiple files spread across various folders. /parentDir/ |__dirA/ |__file1 |__file2 |... |__dirB/ |__file3 |... |... You want to consolidate them into an archive, with the option of using something like ...

Connect various models together, or create synchronized computed properties

At times, the model abstraction may fall short, leading to the necessity of synchronizing two different models. For instance, I have two lists linked by an angular sortable, which requires a model structure like this: left = [{name:"one"}, {name:"two"}]; ...

Tips on setting the default sorting order in AngularJS

I have implemented a custom order function in my controller with the following code: $scope.customOrder = function (item) { var empStatus = item.empState; switch (empStatus) { case 'Working': return 1; case & ...

How can jQuery retrieve a string from a URL?

If I have a URL like http://www.mysite.com/index.php?=332, can jQuery be used to extract the string after ?=? I've searched on Google but only found information about Ajax and URL variables that hasn't been helpful. if (url.indexOf("?=") > 0) ...

What is the best way to extract function bodies from a string with JavaScript?

I am currently searching for a solution to extract the body of a function declaration by its name from a JavaScript code string within a Node.js environment. Let's assume we have a file named spaghetti.js that can be read into a string. const allJs = ...

Problems with Vuex getter reactivity when used in conjunction with Vue router

I've encountered an issue with my Vuex getter that fetches data for the current route and displays it in a Vuetify v-data-table. Everything works perfectly fine when the component is initially created. However, when I add a new entry to the data array ...

JavaScript tool: Verify the presence of both jQuery and jQuery UI

I have been working on developing a Javascript Widget (almost complete), and when integrating it into the first site I encountered some issues. My Widget requires loading multiple libraries (jquery, jquery ui, mustache, ...); this is achieved by injecting ...

Show information - press the button on the current PHP page

After successfully reading files via PHP from a directory and dynamically creating a drop-down menu to view the file content, I have a query. Is there a way to display the text files' content on the same page without calling another PHP page? I know t ...

Experience the auditory bliss with Javascript/Jquery Sound Play

I am creating an Ajax-driven application specifically for our local intranet network. After each response from my Ajax requests, I need to trigger a sound in the client's browser. I plan to store a sound file (mp3/wav) on our web server (Tomcat) for ...