The script functions perfectly in jsfiddle, yet encounters issues when used in an HTML

I stumbled upon a seemingly peculiar issue with my script in jsfiddle: https://jsfiddle.net/oxw4e5yh/

Interestingly, the same script does not seem to work when embedded in an HTML document:

<!DOCTYPE html>
<html lang="en">

<head>
    <script type="text/javascript">
        function calcSpeed(speed) {
            // Time = Distance/Speed
            var spanSelector = document.querySelectorAll('.marquee span'),
                i;
            for (i = 0; i < spanSelector.length; i++) {
                var spanLength = spanSelector[i].offsetWidth,
                    timeTaken = spanLength / speed;
                spanSelector[i].style.animationDuration = timeTaken + "s";
            }
        }
        calcSpeed(75);
    </script>


    <style>
        /* Making it a marquee */

        .marquee {
            width: 100%;
            left: 0px;
            height: 10%;
            position: fixed;
            margin: 0 auto;
            white-space: nowrap;
            overflow: hidden;
            background-color: #000000;
            bottom: 0px;
            color: white;
            font: 50px 'Verdana';
        }
        .marquee span {
            display: inline-block;
            padding-left: 100%;
            text-indent: 0;
            animation: marquee linear infinite;
            animation-delay: 5s;
            background-color: #000000;
            color: white;
            bottom: 0px;
        }
        /* Adding movement */

        @keyframes marquee {
            0% {
                transform: translate(10%, 0);
            }
            100% {
                transform: translate(-100%, 0);
            }
        }
        /* Aesthetics */

        .scroll {
            padding-left: 1.5em;
            position: fixed;
            font: 50px 'Verdana';
            bottom: 0px;
            color: white;
            left: 0px;
            height: 10%;
        }
    </style>
</head>

<body>
    <div class="marquee">
        <span>Lots of text, written in a long sentence to make it go off the screen. Well, I hope it goes off the screen.</span>
    </div>

</body>

</html>

This particular script involves CSS and JavaScript implementation for controlling a steady scrolling speed of the text.

Is there anything specific that I might be overlooking?

Moreover, as observed on the provided fiddle link, there seems to be a noticeable delay before the text starts to scroll. Is there any way to minimize this delay?

Answer №1

It is advisable to call your JavaScript function after the entire DOM has finished loading. One common way to achieve this is by utilizing window.onload like so:

window.onload = function() {
    calculateVelocity(75);
}

Answer №2

If you try to choose an element that hasn't been generated yet,

Make sure to place your script below the marquee code:

<div class="marquee">
<span>This is a long sentence created to go beyond the screen's edge. I really hope it goes off the screen.</span>
</div>
<script type="text/javascript">
function calcSpeed(speed) {
// Time = Distance/Speed
var spanSelector = document.querySelectorAll('.marquee span'),
i;
for (i = 0; i < spanSelector.length; i++) {
var spanLength = spanSelector[i].offsetWidth,
  timeTaken = spanLength / speed;
spanSelector[i].style.animationDuration = timeTaken + "s";
}
}
calcSpeed(75);

</script> 

Answer №3

Ensure to place your script and style codes before the closing of the body tag.

<!DOCTYPE html>
<html lang="en">
<head>

</head>
<body>
<div class="marquee">
<span>A plethora of text, woven into a lengthy sentence to extend beyond the boundary of the screen. Hopefully, it extends off-screen as intended.</span>
</div>
<script>
function adjustSpeed(speed) {
// Time = Distance/Speed
var spanSelection = document.querySelectorAll('.marquee span'),
i;
for (i = 0; i < spanSelection.length; i++) {
var spanWidth = spanSelection[i].offsetWidth,
  timeElapsed = spanWidth / speed;
spanSelection[i].style.animationDuration = timeElapsed + "s";
}
}
adjustSpeed(75);

</script> 


<style>
/* Transforming it into a marquee */

.marquee {
width: 100%;
left: 0px;
height: 10%;
position: fixed;
margin: 0 auto;
white-space: nowrap;
overflow: hidden;
background-color: #000000;
bottom: 0px;
color: white;
font: 50px 'Verdana';
}
.marquee span {
display: inline-block;
padding-left: 100%;
text-indent: 0;
animation: marquee linear infinite;
animation-delay: 5s;
background-color: #000000;
color: white;
bottom: 0px;
}
/* Setting the motion */

@keyframes marquee {
0% {
transform: translate(10%, 0);
}
100% {
transform: translate(-100%, 0);
}
}
/* Adding aesthetic appeal */

.scroll {
padding-left: 1.5em;
position: fixed;
font: 50px 'Verdana';
bottom: 0px;
color: white;
left: 0px;
height: 10%;
}</style>
</body>

</html>

This method proved effective for me!

Answer №4

For optimal performance, it is recommended to place all scripts at the end of your page. This allows the script to find tag ids without encountering errors due to the DOM not being ready.

Example


<html>
    <head>
        <style>
            /* your style here */
        </style>
    </head>
    <body>
        <!-- your html here -->
        <script>
            // your script here
        </script>
    </body>
</html>

For more information, please refer to JavaScript and CSS order

Answer №5

Take a look at this:


function adjustAnimationSpeed() {
  // Formula: Time = Distance/Speed
  var spanElements = document.querySelectorAll('.marquee span'),
    i;
  for (i = 0; i < spanElements.length; i++) {
    var textLength = spanElements[i].offsetWidth,
      timeRequired = textLength / 1000;
    spanElements[i].style.animationDuration = timeRequired + "s";
  }
//adjustAnimationSpeed(10);
}
</script>

<body onload="adjustAnimationSpeed()">

I've personally tested this code on both Chrome and Firefox, and it works flawlessly. Give it a try and let me know how it goes for you.

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

JavaScript: Creating a new entry in a key-value paired array

I am in the process of creating a dynamic menu for use with jQuery contextMenu. I have encountered an issue when trying to add a new element, as it keeps showing the error message 'undefined is not a function'. The menu functions correctly witho ...

The prefixes for Ruby on Rails routes are not properly preprocessed in the .erb.js file

I'm currently working with Rails 4 and encountering an issue with the following file: // apps/assets/javascripts/products.js.erb var getColoursAndMaterialsData = function(onSuccess) { var fd = formdata(); $.post( '<%= data_products_ ...

What is the best way to conceal an element in a loop using React?

I'm facing an issue with this short React code where I'm trying to hide the header that corresponds to a button when that button is clicked. I want only the specific header and button to disappear within the loop. How can I achieve this? For exa ...

Tips for ensuring smaller columns have the same height as their siblings

I'm facing an issue where I have a row with two columns dictating the height, but one of them is shorter than the others. How can I make the shorter column stretch to match the height of the row? This inconsistency in height is causing disruption to ...

Guide to using the ng-click function in Angular to set focus on the input in the last row of a table

I am in the process of developing a task management application and I am looking to implement a specific feature: Upon clicking 'Add Task', a new row is automatically added to the table (this part has been completed) and the input field within ...

Scroll through the div to quickly find the relevant content

I have implemented the following HTML structure: <div style="height:200px;overflow-y:scroll;"> <table>.....</table> </div> By using this setup, I am aiming to replicate the functionality of an expanded <select> control wit ...

Ways to switch the visibility of a specific thumbnail

Our team has created a new app that showcases all the videos in our channel. Users can browse through thumbnails and click on one to view the related video, instead of viewing all videos at once. Angular Code $scope.isvideoPlaying = false; $scope.displ ...

Error-free ngClick doesn't trigger AngularJS controller method

I am struggling to trigger the removePlayer(playerId) method upon clicking a button. However, it seems that the method is not being called, as I have placed a console.log() statement at the top and the console remains empty. This situation has left me puz ...

Having trouble sending a function as a prop to a child component in React

Something odd is happening, I'm confident that the syntax is correct, but an error keeps popping up: Error: chooseMessage is not a function // MAIN COMPONENT import React, { useState } from 'react' export default function LayoutMain(prop ...

What is the process for activating an event before another event on the same element with vanilla JavaScript?

Having an issue with the eventListener function. I am using the external library jquery.jstree-pre1.0fix2, which triggers a blur event on an input in my case. However, I need to trigger my event before the one from the library. I have come across some sol ...

Creating PHP functions that return a JSON string when invoked - a simple guide

I have created a script that contains various functionalities, including fetching data from a database and encoding it into JSON. However, I want to be able to call different functions to execute these scripts separately. When I attempted to define and c ...

Convert data into a tree view in JavaScript, with two levels of nesting and the lowest level represented as an array

Here is an example of a JSON object: [ { "venueId": "10001", "items": [ { "venueId": "10001", "locationId": "14", "itemCode": "1604", "itemDescription": "Chef Instruction", "categoryCode": "28", ...

How to avoid property sharing in Angular recursive components

I am currently working on a recursive component that generates a tree structure with collapsible functionality. However, I am facing an issue where the state variable active is being shared among child components. Is there a way to prevent this from happen ...

The information overflow occurs outside the tooltip specifically in Chrome, while functioning perfectly in IE11

As a newcomer to the CSS world, I am experimenting with adding a block-level element (div) inside an anchor tag's :hover pseudo-class popup. The div element contains a table that needs to have dynamic sizing for both the table itself and its cells (wi ...

iOS creates dynamic images with artifacts that appear on a generated and animated canvas

I am currently developing an HTML5 web application for WeChat, compatible with both iOS and Android devices, using only pure JavaScript without any third-party libraries like jQuery. The main feature of my app involves creating visually appealing animation ...

Scrolling back to the top of the page using Jquery instead of a specific div

Check out the code for my project here. The isotope feature is functioning correctly, however, when clicking on the image, instead of scrolling to the navigation under the red box as intended, the page scrolls all the way to the top. If I modify the follo ...

Implementing a gradient effect on a specific image element within an HTML canvas with the help of jQuery

Currently, I'm working on an HTML canvas project where users can drop images onto the canvas. I am looking to implement a linear gradient effect specifically on the selected portion of the image. My goal is to allow users to use their mouse to select ...

The dividers flicker in and out of view

I have a menu with 7 elements, where clicking on an element causes its content to appear by fading in. If another element is clicked, the current content fades out and the new content fades in. I've successfully implemented this concept for 3 of the 7 ...

Ways to apply CSS styles dynamically within a v-for loop

Despite searching through the VUE official website and various other sources, I have not been able to find a satisfactory solution. I am reaching out for assistance, thank you in advance. <div class="tag-item" :ref="`tagItem_ ...

Navigating through paginated data can be made easier by using Backbone.PageableCollection in conjunction with a personalized

I have developed an application that interacts with a database known as LeanCloud. Currently, I have configured a page to display all the users stored in the database. However, LeanCloud has a limitation where only 100 pieces of data can be retrieved per r ...