javascript horizontal text scroll

I am trying to implement horizontal scroll on my app. I have come across several examples, but none of them seem to fit my specific needs. The code snippet below is one that I thought would work, but it's not functioning as expected. Can someone please help me identify the issue?

<!DOCTYPE html>
<html>
<head>
<style>
div.marquee {
    white-space:no-wrap;
    overflow:hidden;
}
div.marquee > div.marquee-text {
    white-space:nowrap;
    display:inline;
    width:auto;
}
</style>
<script>
var marquee = $('div.marquee');
console.log(marquee);
marquee.each(function() {
    var mar = $(this),indent = mar.width();
    mar.marquee = function() {
        indent--;
        mar.css('text-indent',indent);
        if (indent < -1 * mar.children('div.marquee-text').width()) {
            indent = mar.width();
        }
    };
    mar.data('interval',setInterval(mar.marquee,1000/60));
});
</script>
</head>
<body>
<div class='marquee'>
    <div class='marquee-text'>
        Testing this marquee function
    </div>
</div>

</body>
</html>

Update: There are no errors in the console. https://i.sstatic.net/jSkDh.png

Answer №1

Don't forget to add jQuery to your website for the functionality to work correctly. It seems to be functioning as expected, but including jQuery is crucial.

$(document).ready(function() {
    var marquee = $('div.marquee');
    console.log(marquee);
    marquee.each(function() {
        var mar = $(this),indent = mar.width();
        mar.marquee = function() {
            indent--;
            mar.css('text-indent',indent);
            if (indent < -1 * mar.children('div.marquee-text').width()) {
                indent = mar.width();
            }
        };
        mar.data('interval',setInterval(mar.marquee,1000/60));
    });
});
div.marquee {
    white-space:no-wrap;
    overflow:hidden;
}
div.marquee > div.marquee-text {
    white-space:nowrap;
    display:inline;
    width:auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='marquee'>
    <div class='marquee-text'>
        Testing this marquee function
    </div>
</div>

Edit: I have added $(document).ready() to make sure that all elements are properly loaded before the script runs.

Edit2: For scrolling text from left to right, use the following updated script:

$(document).ready(function() {
    var marquee = $('div.marquee');
    console.log(marquee);
    marquee.each(function() {
        var mar = $(this),indent = mar.width();
        mar.marquee = function() {
            indent++;
            mar.css('text-indent',indent);
            if (indent > marquee.width()) {
                indent = -1 * mar.children('div.marquee-text').width();
            }
        };
        mar.data('interval',setInterval(mar.marquee,1000/60));
    });
});

Answer №2

Ensure the page is fully loaded before running the script.

<script>
$(document).ready(function(){
var marquee = $('div.marquee');
console.log(marquee);
marquee.each(function() {
    var mar = $(this),indent = mar.width();
    mar.marquee = function() {
        indent--;
        mar.css('text-indent',indent);
        if (indent < -1 * mar.children('div.marquee-text').width()) {
            indent = mar.width();
        }
    };
    mar.data('interval',setInterval(mar.marquee,1000/60));
});
});
</script>

Refer to this question for more information, and remember to include

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
in the header section of your website.

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

Implementing Dynamic Weight-based Pricing with CodeIgniter and AJAX

My shopping cart website utilizes ajax and Codeigniter to add products without reloading the page. Originally, I displayed a single net weight for each product. However, I recently switched to multiple net weights for the same product. Unfortunately, I am ...

What is the equivalent of getElementById in .ts when working with tags in .js?

Looking to incorporate Electron, Preload, Renderer with ReactJS and TypeScript into my project. <index.html> <body> <div id="root" /> <script src='./renderer.js'/> </body> <index.ts> const root = Re ...

Are components accessible through the console in a production environment?

After finishing a website project for my friend using React, Express, MongoDB, and more, I noticed that one of the components can be accessed via console.log. Is this normal behavior for a component to be accessible in this way? It's concerning becaus ...

What is the best way to explain the concept of type indexing in TypeScript using its own keys?

I'm still learning TypeScript, so please bear with me if my question sounds basic. Is there a way to specify the index for this type so that it utilizes its own keys rather than just being an object? export type TypeAbCreationModal = { [index: stri ...

Input various information into a single form multiple times and automatically submit it to a Google spreadsheet

I have some data that needs to be transferred to an array and then sent to a Google Sheet. The data looks like this: -|PO: 2005 | 12121211212121,| Qty: 45| BIN:110| eBay| 11/6/2017-| PO: 2165 | 333333333,| Qty: 54| BIN:20| google| 11/6/2017- First, I use ...

Personalizing navigation tabs using Bootstrap

I've been working on creating a custom bootstrap navbar tabs, but I'm struggling to remove the borders and apply the custom colors. After some trial and error, here's what I have so far: .nav-tabs, .nav-pills { text-align: center; bo ...

Ensuring that one then() statement waits for the other to finish before executing

My React application is connected to Firestore DB, and I'm fetching data in the componentDidMount() lifecycle method. I handle two then() calls - one for retrieving data from the DB and saving it, and the other for updating the component's state. ...

What is the process of embedding a string with pug code into a pug file?

How can I interpolate a string with pug formatted code in a pug file? Here is what I have tried: - var text = "i.home.icon" div= text div !{text} div #{text} div ${${text}} div {{text}} div {text} div \#{text} div \{text} div ${text} div # ...

Incapable of stopping a form submission when a certain criteria is satisfied

I am currently working on a form validation system using jQuery $.ajax. The aim is to only allow submission of the form if a specific condition, data == 1, is met. var preventSubmit = function() { return false; var form = $(this), name = form.find ...

Arranging expandable divs horizontally

Looking for a way to align these blocks so they can expand while remaining in line, I'm struggling with maintaining their individual spaces. The layout I have in mind is as follows: In this setup, box 2 and 3 should automatically adjust to fill the a ...

The webpage is missing specific rows from a query in a Flask project

I need assistance in setting up a database that allows users to select IDs extracted from MySQL databases. However, I am encountering an issue where the results are not displaying on the webpage. Initially, I suspected it was due to the font color, but aft ...

What is the correct way to insert a Vimeo video into an HTML document?

When embedding a YouTube video in HTML, the <iframe src="https://youtube.com/embed/videoId> element is used. But what about when you want to embed Vimeo videos using the <iframe> element? ...

Angular Component Caching

I am currently working with two Angular components. The first component displays a list of picture items that are fetched from a server. When the user selects a picture, they are taken to the second page where additional information is shown in a detailed ...

What is the best way to align two navbar elements to the right in Bootstrap 5?

I've been attempting to position two elements at the end of the Bootstrap 5 navbar, but I haven't been successful. I've experimented with using ms-auto within a div that wraps around the login and sign up elements, but that hasn't work ...

What is the best way to arrange numerous objects within an array?

Here is the code snippet I am working with: const info = { detail : { id: "1", name: "aa", category: [ { id:"11", order:0, }, { id:"33", order:5, }, { id: ...

Validating Angular UI without requiring an input field (validating an expression)

Currently, I am utilizing ui-validate utilities available at https://github.com/angular-ui/ui-validate The issue I am facing involves validating an expression on a form without an input field. To illustrate, consider the following object: $scope.item = ...

Validation conditions with ASP.Net Razor Pages

Working with ASP.Net Core 2.2 razor pages and Bootstrap 4, where users input family member information. The form serves both for adding and editing members, calling different handlers. If an email is not provided, a modal confirmation is displayed. Current ...

Having trouble populating Extjs Grid with JSON data

In this simple grid, I am attempting to display three columns - Subject ID, Subject Name, and Subject Short Name by obtaining JSON data. The data is stored in a variable called myData in JSON format, which has been received from the server. Despite pasting ...

Avoid using `@typescript-eslint/no-floating-promises` when using a `const` function

Can anyone help me understand why the @typescript-eslint/no-floating-promises rule works with some async functions but not all? To my understanding, these two functions should be equivalent: const getUser = async (userId: string): Promise<User> => ...

Expanding list selection with jQuery_hover effect

I have devised the following code. HTML <ul class="treatment-menu"> <li>Menu always visible</li> <ul class="nav-child"> <li>Hidden sub menu</li> </ul> </ul> Hover function $(&a ...