interval-based animation

I'm trying to create a simple animation using setInterval in JavaScript. The goal is to make an image move from left to right.

HTML:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
    <title>animation</title>
    <style type="text/css">
    #image
    {
        position: relative;
        left: 1px;
    }
    </style>
    <script type="text/javascript"  src="animation.js"></script>

</head>
<body>
    <img src="smile.jpg" id="image" alt="Smile" width="100" height="100" />
</body>
</html>

JavaScript:

window.onload = initialize;

function initialize()
{
    setInterval(function(){animate();},1000);
}

function animate()
{
    var obj = document.getElementById("image");
    var value = parseInt(obj.style.left, 10);
    obj.style.left = (value + 10) + "px";
}

Unfortunately, the JavaScript code isn't working as expected and I'm not sure why. The animate function is executing but the image's position is not changing.

Answer №1

There appears to be a small bug in your code...

At the beginning, when the left property of the element is not specified, it defaults to being empty. This causes parseInt to return NaN.

To fix this issue, you can simply add an additional check condition.

window.onload = initialize;


function initialize()
{
    setInterval(animate,1000);
}

function animate()
{
    var obj = document.getElementById("image");
    var left = obj.style.left;
    if(left === ''){
        left = 0;
    }
    var value = parseInt(left, 10);
    obj.style.left = (value + 10) + "px";
}​

View Fiddle

Answer №2

The issue you're facing is that the obj.style only contains information about styles defined within the style tag itself, not any styles specified in external style sheets like your <style> tag. Because of this, when trying to access obj.style.left, it returns an empty string leading parseInt('') to result in NaN.

To resolve this, make sure to define your left style property directly in the style attribute of the <img> tag:

<img ... style="left:1px;" />

Alternatively, if maintaining separate styles is crucial (e.g., following specific design standards), you can utilize the window.getComputedStyle function to determine the actual left style value for the object:

function animateObject()
{
    var obj = document.getElementById("image");
    var value = parseInt(getComputedStyle(obj).left, 10);
    console.log(parseInt(getComputedStyle(obj).left, 10))
    obj.style.left = (value + 10) + "px";
}​

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

Establishing a default selection for a react dropdown menu filled with data retrieved from an API request

class Select extends React.PureComponent { constructor(props) { super(props) this.state = { value: this.props.initialValue } this.handleChange = this.handleChange.bind(this) } handleChange(e) { e.persist() ...

Steady Navigation Bar in Javascript without Bouncing

While experimenting with a fixed navigation bar, I've encountered an issue where the content below jumps up on the page when the navigation bar "fixes" itself to the top of the screen. You can check out the JSFiddle I've been working on for refer ...

Multiple requests were made by Ajax

I am facing an issue with my ajax code where it is being called multiple times. Below is my php code: (While loop extracts results from a database. For brevity, I have included just the modal and dropdown menu sections.) $rezPet = mysqli_query($kon, "SEL ...

When using v-select to search for items, the selected items mysteriously vanish from

I recently worked on a project where I encountered a similar situation to the one showcased in this CodePen. Here is the link to the specific CodePen One issue I faced was that the selected items would disappear when performing an invalid search. After i ...

Tips for designing scrollable overlay content:

I am currently in the process of building a page inspired by the design of Hello Monday. Right now, I have added static content before implementing the parallax effect and auto-scroll. Here is my progress so far: Check out the Sandbox Link One challenge ...

Saving an Axios request array to a Laravel controller in Laravel using VueJs

I am working on a laravel 5.7 application that utilizes VueJS 2.0 for the front end. The issue I am facing involves two tables with a many-to-many relationship: 'commandes' and 'produits'. When trying to pass data into my 'commande ...

Executing a closure within a promise's callback

Currently, I am working on implementing a queue system for a web application in order to locally store failed HTTP requests for later re-execution. After reading Mozilla's documentation on closures in loops, I decided to create inner closures. When ...

I am experiencing issues with the functionality of front-page.php on my WordPress website

Seeking guidance in addressing a web development issue: I have encountered a problem with a website that I am currently working on locally using WordPress. I added the following code to the header.php file: <link rel="stylesheet" type="text/css" href= ...

Swapping out ChildNode data for HTML elements

When attempting to replace a node value with HTML content, I encountered an issue where the HTML tags were being displayed on the HTML page instead of applying the intended style. <style> .YellowSelection { background: yellow; } < ...

Ways to layer two divs on each other and ensure button functionality is maintained

In the process of developing a ReactJS project, I encountered the challenge of overlapping my search bar autocomplete data with the result div located directly below it. For a more detailed understanding, please take a look at the provided image. Here&apo ...

Encountering the error message "The getStaticPaths function in Next.js requires the 'id' parameter to be provided as a string"

Having an issue with the getStaticPaths function. Every time I attempt to create a dynamic display using a parameter, it gives me an error message: A required parameter (id) was not provided as a string in getStaticPaths for / movies / [id]. However, if ...

Is it possible that adding html tables together could result in the numbers being concatenated instead of summed?

When attempting to calculate the total sum of values in an html table column, my variable seems to be returning concatenated strings instead of the actual sum. For example, instead of 1 + 2 + 3 = 6, I am getting 1 + 2 + 3 = 123. The values in the "votes" ...

Creating an Add-in using the Excel JavaScript API based on an already existing spreadsheet

Is there a way to create an Add-in using Excel JavaScript API from an existing spreadsheet? When running npm start, it generates a blank workbook. I believe changes need to be made in the Manifest.xml file, as npm start triggers office-addin-debugging star ...

Issue with Ajax/Json: "An object of type triggers a circular reference error when attempting to retrieve a list."

Recently, I encountered an issue with my server-side method that is triggered through JSON/Ajax. The method itself functions flawlessly and sends back a list as expected. However, I seem to have made an error in my JavaScript code, leading to the following ...

Redux application is not functioning properly

I followed the official documentation to create a Redux app at http://redux.js.org/docs/basics/ but it's not working as expected. I have organized my code into four files: store, reducers, actions, and build. actions.js: export const ADD_TODO = &apo ...

The second AJAX request isn't functioning properly; it should only be executed once the first one has successfully completed

I am experiencing an issue with my ajax calls. The second call should only be triggered after the first one is successful. However, even though the first call always returns success, I keep getting an error for the second one. function proceedWithUnlock(t ...

The issue arises when the d3 startAngle and endAngle values are set to NaN, resulting in an

I am working with a dataset that includes the following information: { current: 5 expected: 8 gap: -3 id: 3924 name: "Forhandlingsevne" progress: "0" type: 2 } Now, I have implemented the ...

How to Retrieve the Absolute Index of the Parent Column Using jQuery Datatables

I recently developed a custom column filtering plugin for datatables, but I've encountered a minor issue. Within each column footer, I have added text inputs, and now I am trying to capture their indexes on keyup event to use them for filtering. In ...

Is there a way to deliver information to a specific element on a client's HTML page?

My current project involves using Node.js to serve a webpage that collects user inputs and stores them in a mongodb server. The web page also displays these user inputs. I am trying to determine the best way to pass the user inputs from node.js to the < ...

Ways to conceal an element in Angular based on the truth of one of two conditions

Is there a way to hide an element in Angular if a specific condition is true? I attempted using *ngIf="productID == category.Lane || productID == category.Val", but it did not work as expected. <label>ProductID</label> <ng-select ...