issue with animation occurs when the value changes while the setTimeout timer is still running

function wallpaperMediaPropertiesListener(event) {

    // reset animation
    test.stop(true);
    test.css('margin-left', 0);
    
    // set song title.
    test.text(event.title);
    var testWidth = test.outerWidth();
    
    // clone text
    $('.test-copy').remove();
    if (testWidth > $('#line1').width()) {
        test.clone().css({'margin-left': gap, 'font-size': '1.05vh'}).removeClass().addClass('test-copy').insertAfter(test);
    }
    
    // move text
    let speed = 5;
    function shiftingAnimation() {
        let timer = setTimeout(() => {
            test.animate({'margin-left': -(testWidth + gap)}, {
            duration: Math.abs((testWidth + gap) * 100 / speed),
            easing: 'linear',
            complete: function () {
                test.css({'margin-left': 0});
                clearTimeout(timer);
                shiftingAnimation();
            }
            });
        }, 3000);
    }

    // first execution
    if (testWidth > $('#line1').width()) {
        setTimeout(shiftingAnimation, 3000);
    }

}

event.title returns the name of the song currently playing. The wallpaperMediaPropertiesListener function is triggered when there is a change in the song.

The animation starts after a 3-second delay when testWidth is greater than #line1 width. Once the animation ends, it repeats itself with a 3-second delay each time. If the event.title value changes, the animation resets and starts from the initial 3-second delay again.

However, the issue arises when the event.title value changes during the 3-second delay. The animation is applied regardless of whether the condition (testWidth > #line1) is true or false, and it appears to be using the previous testWidth for the animation.

Answer №1

Make sure to pass the event title as a parameter, not the entire event object:

1 - When calling your function, include only the event.title

wallpaperMediaPropertiesListener(event.title)

Then proceed with the following code snippet:

`function wallpaperMediaPropertiesListener(title) {

// reset the animation
test.stop(true);
test.css('margin-left', 0);

// set the song title
test.text(title);
var testWidth = test.outerWidth();

// clone text if too wide
$('.test-copy').remove();
if (testWidth > $('#line1').width()) {
    test.clone().css({'margin-left': gap, 'font-size': '1.05vh'}).removeClass().addClass('test-copy').insertAfter(test);
}

// move the text
let speed = 5;
function shiftingAnimation() {
    let timer = setTimeout(() => {
        test.animate({'margin-left': -(testWidth + gap)}, {
        duration: Math.abs((testWidth + gap) * 100 / speed),
        easing: 'linear',
        complete: function () {
            test.css({'margin-left': 0});
            clearTimeout(timer);
            shiftingAnimation();
        }
        });
    }, 3000);
}

// initiate the animation
if (testWidth > $('#line1').width()) {
    setTimeout(shiftingAnimation, 3000);
}

}`

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

MongoDB Stitch retrieves all data fields

Can anyone help me with my MongoDB query issue? I've recently started working with mongoDB and I'm having trouble getting just one field back for all my documents. var docs = db.collection("articles").find({}, { _id: 0, title:1}).asArray(); De ...

Transfer shader program with buffers from shadertoy to three.js

Currently, I am delving into the world of webgl and shaders to enhance my understanding and skills. My objective is to create animations for website backgrounds. I have successfully imported basic examples from shadertoy into three.js and have been experim ...

Eliminate the standard blue border that appears when control-clicking on table elements

I've encountered this question before, but unfortunately none of the solutions provided have worked for me. Some things I've attempted are: Using event.preventDefault() - did not produce the desired result. Removing user-select from CS ...

React Router's nested route causes a full page reload when navigating

I have been working on setting up nested routing in React Router and here is my code: import React from 'react'; import DefaultSwitch from './components/DefaultSwitch/DefaultSwitch'; import './scss/App.scss'; const App = () ...

Make sure to include the "active" class in the pager once the slider begins

After coming across this fiddle, I noticed that it closely resembles the task I am working on. However, there is one issue - currently, only the first item has an active class when the slider autostarts. The next or previous items do not receive the acti ...

Disabling a button until all textfield fields are completed: A Step-by-Step Guide

My modal contains a table with the following code structure. <div> <Table> <tbody> {props.data.map((p) => <> <tr> <th> STC </th> ...

jQuery is not recognizing the checked state of a checkbox when it is modified dynamically

$("#submit_load").click(function() { var profilename =$("#search_profiles option:selected").attr("value"); var data='profilename='+profilename+'&user_id=' + <?=$user_id;?>; alert(data); $.ajax({ //this is ...

Retrieving the value of an inner div upon clicking the outer div

I currently have a collection of button divs, each containing distinct information: <div class="button"> <div id="first"> Johny </div> <div id="second"> Dog </div> <div id="third"> Pasta & ...

Is there a way to retrieve the value of an HTML form in order to utilize it within a JavaScript function

I am currently working on developing a temperature converter that utilizes a single number input form. When the form is submitted, it should convert the temperature to either Fahrenheit or Celsius. Unfortunately, as a beginner in JavaScript, I have limited ...

Struggling to adjust the quantity of items in a basic shopping cart when adding multiples of the same item

Hello there! I'm currently working on a project where I need to increase the quantity of each item added to the cart if it's already in there. This is actually my first time posting, so any tips on asking better questions would be greatly appreci ...

Working with npm objects across multiple files

My goal is to integrate the npm package for parallax (lax.js) into my project. The documentation states that in order to initialize it, the following code snippet should be included: window.onload = function () { lax.init() // Add a driver that we use ...

Covering the full width of the page, the background image

My struggle is with setting a background image to 100% width, as the image ends up getting cut off on half of the screen. The picture becomes wider than my display area. How can I resolve this issue so that the image width adjusts to fit the screen without ...

Creating interactive animations in Jquery by clicking on one object to trigger animation of another object

I've created a cool soundboard with interactive buttons. Each button plays a unique sound when clicked and changes appearance when hovered over. However, I'm facing a challenge in animating an image to move from the left side of the screen to 500 ...

Is it possible to automate the process of clicking the "next" or "previous" button on a webpage after a video has finished playing?

Is it possible to automate clicking the "next" or "previous" button on a specific website? The buttons are not labeled as such but instead show the cartoon name and episode number. For example, increasing episode numbers indicate the "next" episode while d ...

I am experiencing issues with my HTML select list not functioning properly when utilizing a POST service

When using Angularjs to automatically populate a list with *ngFor and then implementing a POST service, the list stops functioning properly and only displays the default option. <select id="descripSel" (change)="selectDescrip()" > <option >S ...

Why am I unable to access the array once the loop has finished?

While utilizing the Google Maps API and AngularJS (1.5.8), I encountered an issue where I couldn't access markers that were created in a loop. The code snippet below is located inside the initMap function: var markers = []; for(var i=0; i<10; i++ ...

Import information from a MySQL table into a single input field

I am currently working on a project that involves retrieving data from a MySQL database and displaying it in a single field. Below is the MySQL code I am using: My goal is to load all the data from $row['db_numbers']; into the field. <input t ...

Seems like JavaScript's .active functionality is failing to function properly in my case

I'm encountering an issue with my website's homepage. I have a list of services displayed, and the intention is for a description to appear when one of the services is clicked. However, clicking on the buttons does not trigger the expected action ...

Library for visualizing JavaScript code using flowcharts and diagrams

Is there a jQuery-based javascript library available for client-side rendering and manipulation of flow-charts? I am open to other options as well. This question has been previously posed, but has not been revisited in a few years. Hopefully, there are ne ...

I am looking to arrange two div elements and one navigation bar into the header, positioning them at the top-left, top-center, and top-right using CSS. How

I'm attempting to arrange three divs within the <header>: div1 (logo) at the top left of the page, nav2 (menu bar) at the top center of the page, and div3 (social networks) at the top right of the page. However, I am unsure of how to achieve thi ...