Persistent JavaScript animation loop troubles

Hey there, I'm new to web development and I've been working on a simple webpage with a text animation that moves from the top of the screen to the middle when the page loads. The animation itself is working fine, but I'm having trouble stopping the loop. Even though the animation stops visually, I suspect that the function is still looping in the background. This causes other elements on the page, like links, to malfunction because the JavaScript is technically still running. Any tips on how I can properly end the function? Thanks!

window.onload = Animation;
function Animation() {

    // Get element and determine text's initial position.
    var Element = document.getElementById("AnimationText");
    var Position = -500;

    var ID = setInterval(OnFrame, 20);

    function OnFrame() {
        if (Position > 50) {
            clearInterval(ID);
        } else {
            if (Position > -100 && Position <= 0) {
                Position = Position + 3; // Middle of animation
            } else if (Position > 0) {
                Position = Position + 2; // End of animation
            } else {
                Position = Position + 4; // Start of animation
            }
            Element.style.top = Position + 'px';
        }
    }
}

HTML:

<!DOCTYPE HTML>
<html>
<head>
    <link href="https://fonts.googleapis.com/css?family=Sedgwick+Ave" rel="stylesheet">
    <link href="HomepageStyle.css" rel="stylesheet" type="text/css">
    <script src="HomepageAnimation.js"></script>
</head>
<body>
    <div id="AnimationText">
        <h1>TNT</h1>
    </div>
    <center>
        <a href="LogIn.html">
            <img src="_assets/LoginButtonHome.png" style="margin-right: 40px; margin-top: 400px;">
        </a>
    </center>
</body>
</html>

Answer №1

After testing your code in a sample HTML document and inserting console logs to track the function's execution post clearInterval, it appears that the function does not execute. Feel free to verify this by adding two console.log statements - one within the if statement and another within the else statement.

Alternatively, you may want to experiment with the following modification to address your issue:

if (Position > 50) {
    clearInterval(ID);
    console.log("Execution ended"):
    ID = null;
    return;
}

Here is the test HTML element I used:

<p id="hello" style="position: absolute;">My first paragraph.</p>

To access the JSFiddle link for further testing, click here: Test here!

If you wish to view the console logs in Chrome, navigate to: View -> Developer -> JavaScript Console

Answer №2

You can utilize JavaScript to simply add a new class and allow CSS to take care of the rest:

Here is an example with HTML, JS, and CSS:

<div id = "AnimationText" class="init">
  <h1>Explosion</h1>
</div>

JavaScript:

document.getElementById("AnimationText").classList.add("middle");

CSS:

#AnimationText {
  transition: all 4s ease;
}
.init {
  margin-top: -150px;
}
.middle {
  position: relative;
  margin-top: 200px;
}

https://jsfiddle.net/o25fp7jg/1/

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 compare all the elements in an array to the entries in another object, while also storing the results of each comparison?

I am working with a JSON file that contains an array of 2 objects: `{ bg: 'a', o: 'c' }`, `{hg': 'a2', 'oo': 'c3'}`. My goal is to compare each object in the array with another object structured as fol ...

Exploring the Integration of HTML5 with Android

I recently began diving into Android development and want to incorporate HTML5 as a cross-platform technology. However, I'm not familiar with HTML5 or how it interacts with Android. Despite my efforts to research this topic, I still feel lost on where ...

The result of the $.post() request is back

In my current code, I am using a jQuery $.post function like this: $.post('/test', json_data, function(data) { result = data }); This function is being used in a validation process where the return value (data) contains either true or false ...

Extracting graph coordinates from a webpage using web scraping

Looking for assistance with web scraping to extract player rankings from a graph displayed in this link Simply visit the link, click on Rating, and hover over the plotted points. The y-coordinate will be visible along with other relevant information that ...

Leveraging a web component in JavaScript with ReactJS

There is an abundance of resources available on how to implement a WebComponent using JSX in React. It's a fairly straightforward process... However, the question arises - how can one use a web component in JavaScript with ReactJS? render: function( ...

Accessing JSON data model from Ember route or controller

Exploring the capabilities of Ember.js Is it possible to expose my data model as JSON through a route or controller? The object saved in the store looks like this: this.store.createRecord('Person', { id: 1, name: this.get('name'), ...

Replacing a broken image URL with a default one when the broken URL is inaccessible

I am currently developing a search tool for a company where employees can easily find their names through json data retrieval. This data includes links to images of the employees. Here's my question: Sometimes, the image link may not exist due to inc ...

Tips for inserting user input into an array and showcasing it

const [inputValue, setInputValue] = useState(""); return ( <input onChange={(event) => setInputValue(event.target.value)} /> <p>{inputValue}</p> ); I'm facing a problem where I need to take input from a user and store it in ...

Troubleshooting: Why isn't my Axios PUT request functioning properly?

My issue is that axios.put method isn't working, but axios.post works perfectly fine. Here's an example of a successful post request: let response = await axios.post(`${ROOT_URL}/urls/url/`, { post_id, password, content }, { heade ...

What are some additional options for sourcing images in the img HTML tag?

I am facing an issue where I have two alternative images, with one image set as the default if the first two are not found. <img src='image1.png' onError="this.onerror=null;this.src='image2.png';" onError=" ...

Use jQuery to retrieve the response from a JSON request and showcase it on the existing HTML page

Currently, I am working on a project that involves integrating a JSON-based web service from a remote server. The method of this service can be accessed by using specially formatted URLs such as: http://root-url/ws/service-name?request={json-string} The ...

What is the best way to obtain the output produced by a function when a button is clicked

When I click on a button, the desired action is to trigger a function that adds a new property inside an object within a large array of multiple objects. This function then eventually returns a new array. How can I access and utilize this new array? I am ...

Looking to dynamically assign a value to ngModel that comes from user input in Angular version 4

Within this context, we have two distinct addresses for shipping and billing purposes, each with its own unique value. To handle this scenario, we have leveraged reusable components, specifically a select-country component. <select-country [addressType ...

Display CSS specifically to the super administrator

I am trying to customize the appearance of certain tables in the WordPress dashboard using CSS so that they are only visible to super admins. <?php is_super_admin( $user_id ); ?> add_action( 'admin_head', 'my_custom_function' ); ...

Locate the HTML code following an AJAX response

JavaScript code snippet: $("#category select").change(function(){ var category = $('select option:selected').html(); $.ajax({ type:"Post", url:"collectiepost.php", data:"category="+category, cache:"false" ...

What is the best way to retrieve the data stored in a TD element within a TR row in an HTML table?

How can I retrieve the value of a clicked table cell? https://i.stack.imgur.com/HfXBK.png <table id="table" class="table" style="margin-right: auto; margin-left: auto" > <thead> <tr> <th>Request Number</th> ...

Tips for maintaining space beneath an image when text wraps around it

.blogimgarea { width: 38%; padding-right: 26px; float:left; } img{max-width:100%} .blogtextarea { width:55%; padding:22px 32px 0 0; float:right; } <div class="newpostregion pt70"> <div class="blogimgarea"> <img class="featblogimg" src="https ...

"Exploring the world of Reactstrap: A

I am struggling to understand the documentation for Bootstrap and reactstrap as I have never used them before. For example, changing the Navbar color and background opacity has been a challenge because they require reserved keywords to be passed as props, ...

Navigate through AJAX Live search using arrow keys and mouse controls

I have encountered an issue with the autocomplete feature on my webpage. Although I am able to input suggestions, I am unable to navigate through them using the mouse pointer initially. Oddly enough, if I press the up/down keys once after the list items ar ...

Navigating redirects in HTML parsing with Python

I am currently experimenting with submitting multiple forms using a Python script and making use of the mechanized library. The purpose behind this is to set up a temporary API. The issue I am encountering is that upon form submission, a blank page appea ...