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

What is the best way to align a button within a Jumbotron?

Struggling to find the right CSS placement for a button within a jumbotron. I attempted using classes like text-left or pull-left, but nothing seemed to work as I hoped. I believe a simple CSS solution exists, but it's eluding me at the moment. Ideall ...

What is the best way to target and manipulate the transform property of multiple div elements in JavaScript?

Looking at this code snippet, my goal is to have all the boxes rotate 180deg with a single click, without needing to apply different ID names: function rotateAllBoxes() { var boxes = document.getElementsByClassName("box"); for (var i = 0; i < box ...

Convert a two-column layout on the web into a single-column layout for mobile devices, featuring dynamic

Is there a way to style this diagram with CSS that will work on IE11 and all major browsers? It seems like Flexbox doesn't support dynamic height. Do I need separate left and right columns for larger viewports and no columns for smaller viewports? ...

The issue arises when attempting to execute an Ajax function within a JQuery append method, causing malfunction

My JQuery append function is calling an ajax function within the onChange method. Here is my code snippet: var data='<?php echo $data; ?>'; var tambah=1; var txt=1; function add_fullboard_dalam_kota(){ function showU(str) { ...

Invoke data-id when the ajax call is successful

Initially, there was a smoothly working "like button" with the following appearance: <a href="javascript:void();" class="like" id="<?php echo $row['id']; ?>">Like <span><?php echo likes($row['id']); ?></span ...

Is there a way to effortlessly generate a mini-website from Markdown files?

Can a tool be found that creates a mini-website from locally-stored Markdown files complete with automatically generated navigation? I'm hoping for a service that can sync with my Dropbox, analyze the file structure, read the Markdown files, and effo ...

Is it possible to save the project by generating incremental JSON diffs?

In the process of developing a web-based paint program, I have implemented a system where the user's artwork state is saved as a json object. Each time an addition is made to the client's undo stack (which consists of json objects describing the ...

Update the styling of buttons in CSS to feature a unique frame color other

Can anyone help me with styling Bootstrap buttons and removing the blue frame around them after they're clicked? Here's what I've tried: https://i.stack.imgur.com/jUD7J.png I've looked at various solutions online suggesting to use "ou ...

Additional GET request made after update request

After the user updates their contact information in the frontend application, the state is updated and a PUT API request is made to update the current information. When updating user contact details with a PUT call, should another GET call be made to retr ...

I'd like to know what sets next/router apart from next/navigation

Within Next.js, I've noticed that both next/router and next/navigation offer a useRouter() hook, each returning distinct objects. What is the reasoning behind having the same hook available in two separate routing packages within Next.js? ...

Click on the window.location.href to redirect with multiple input values

I am facing a challenge with my checkboxes (from the blog label) and the code I have been using to load selected labels. However, this code seems to only work for one label. Despite multiple attempts, I have found that it only functions properly with one ...

Can the text value be read and its strings changed?

I need to modify the message inside an H2 element with the code provided below. I want to change the text from No results were found for this query: <em class="querytext"> to "No results were found by hello world!, but the catch is that I cannot di ...

Can CSS stylesheets be set up to automatically load based on the browser being used to access the website?

I am inquiring because I recently completed a beautiful homepage design and, after viewing the website on Chrome and Safari on OSX, I noticed that certain elements were broken when I opened it in Firefox. In addition, an issue I was experiencing with the ...

The element selector for the <code> tag is not recognized in SCSS

Update on 2020/02/23: I have made some additions to my project. Apologies for the lack of information provided earlier. The project I am working on is a modified version of the [Gatsby + Netlify CMS Starter][1]. In the process, I swapped out all.sass wit ...

Tips for utilizing multiple ngFor directives for property binding within a single directive

After implementing the ng-drag and drop npm module with the draggable directive, I encountered an issue while trying to display a list of items from a 2D array using li elements. Since multiple ngFor's are not allowed in Angular, I needed to come up w ...

Tips for Implementing a "Please Hold On" Progress Bar in ASP.NET

I have a master page named siteMaster.master, an aspx page called submission.aspx, and a user control named attachment.ascx. The script manager is included in my master page. The submission page inherits the master page and registers the user control attac ...

Prevent zooming or controlling the lens in UIWebview while still allowing user selection

Is there a way to disable the zoom/lens on uiwebview without affecting user selection? I'm trying to avoid using "-webkit-user-select:none" in my css. -webkit-user-select:none ...

Send the user authentication form to a different location by using an AJAX request

I am in the process of developing a .Net Web application using ASP MVC, jQuery & AJAX. Within this application, I have a list of products. When a user clicks on the detail button of a specific product, they are taken to a details view which includes an "Ad ...

Pattern matching: Identify text elements specifically within an HTML tag

I've been experimenting with a text highlighting script. Check out my initial attempt here. Here's the code snippet: http://jsfiddle.net/TPg9p/3/ However, I encountered a problem – it only works with simple strings and not those containing HT ...

Issue with ExpressJS Regex not correctly matching a path

I'm currently struggling with a simple regex that is supposed to match words consisting of letters (0-5) only, but for some reason it's not working as expected. Can anyone help me figure out the correct expression and how to implement it in Expre ...