What issue could be causing trouble with my JavaScript animation?

Currently, I am working on designing a web-page and I have a specific vision in mind - I want an image of the moon to slowly rise up from the bottom of the screen to the top. Here's the HTML code that I have so far:

<body>
    <div id="Moon" onload="Moon()"></div>
</body>

For the CSS styling, here is what I have:

#Moon{
    width: 150px;
    height: 150px;
    left: 50px;
    top: 600px;
    background: transparent url(../Img/Moon.SVG) no-repeat ;
    position: absolute;
}

And here is the JavaScript code for the animation effect:

function Moon(){
    var Moon=document.getElementById("Moon");
    var yposition=Moon.style.top;
    var id = setInterval(frame, 10);
    function frame(){
        if (Moon.style.top > 100) {
          yposition--; 
          Moon.style.top = yposition + 'px'; 
        } else {
          clearInterval(id);
        } 
        frame();
    }
}

Unfortunately, despite my efforts, the image of the moon remains fixed at the bottom of the page without any movement. Any insights or suggestions on how to resolve this issue would be greatly appreciated.

Answer №1

Here is a suggestion.

If you want to calculate the top offset of a div, you can use the moon.offsetTop property. Remember, a div does not have an onload event, so you will need to trigger your Moon() function either through a script or the body onload event.

function Moon(){
    var moon=document.getElementById("Moon");
    
    var yposition= parseInt(moon.offsetTop) ;
  
    var id = setInterval(frame, 10);
  
    function frame()
    {
        if (moon.offsetTop > 10) {
          yposition--; 
          document.getElementById("Moon").style.top = yposition + 'px'; 
        } else {
          clearInterval(id);
        } 
    } 
}
#Moon{
    width: 300px;
    height: 250px;
    left: 50px;
    top: 600px;
  background: transparent url("https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcQh7mGmBMJ--wS711QkCEPHHS56jV15VmESttDbVLZPSI_FsMAyTQ") no-repeat ;
    position: absolute;
    
}
<body onload="Moon()">
<div id="Moon"></div>
  </body>

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

Why is the UI Router controller failing to function properly after loading the view from the $templateCache?

I've been utilizing gulp-angular-templatecache to convert my filename.view.html files into a consolidated templates.js file. Afterwards, I use $stateProvider to define states and fetch the templates from $templateCache, including an abstract "root" s ...

What steps can I take to hide my textarea after it has been clicked on?

Recently, I reached out for help on how to make my img clickable to display a textarea upon clicking. While I received the solution I needed, I now face a new challenge - figuring out how to make the textarea disappear when I click the img again. Each clic ...

Unable to Apply Margin to Element within ASP.Net View Code Section

I've exhausted all my ideas and even searched Google without finding a solution. <div class="col-md-12"> <div class="card-header text-white" style="background-color:cornflowerblue"> <div class=& ...

issue with AngularJS model not initially binding to select dropdown

I am facing an issue with a select dropdown in my code. I am using ng-repeat to populate the dropdown like this: <select ng-model="tstCtrl.model.value" required> <option ng-repeat="option in tstCtrl.myOptions" value="{{option.a}}">{{option.b ...

In Vue, you can dynamically load a JavaScript file containing a JavaScript object during runtime

I'm in the process of developing a no-code application with Vue. I have come across an issue where I cannot add functions to a JSON file that I want to import at runtime. As a workaround, I decided to use a JavaScript or TypeScript file to store the J ...

Nuxt's axios is encountering difficulties in managing the server's response

Having just started working with Nuxt.js, I encountered an unusual issue. There is an endpoint in my backend API that allows users to reset their password by sending a token along with a new password. Although the request is being sent correctly and the s ...

Removing cookies after sending a beacon during the window unload event in Chrome

Here's the situation: I need to make sure that when the browser is closed or the tab is closed, the following steps are taken: Send a reliable post request to my server every time. After sending the request, delete the cookies using my synchronous fu ...

Switch a Laravel Collection or Array into a JavaScript Array

Is there a way to transfer data from Laravel to a JavaScript array? I have extracted the data from my AppServiceProvider and decoded it using json_decode, as shown below: View::composer('*', function($view) { $users = Users::all(); $view-& ...

CSS: Create a form with two input fields where the left field is adjustable in width and the right field fills up

------------- -------------------------------------------------- | some unique text | | some more original content, varying length | ------------- -------------------------------------------------- |<---------------------- 100% width ------------------ ...

Looking for a way to connect a background image in Vue CLI?

When running the code below, I encounter an issue. The code runs properly but the images are not displaying and instead showing the URL as unknown. How can I fix this problem? The images definitely exist. <template> <div class="slider">< ...

items within the grid container are positioned without being constrained to rows and columns

After using the Container element, I noticed that all my grid items are displaying in columns instead of rows. How can I correct this layout issue? https://i.stack.imgur.com/9BjOA.png Click here to access the project link. ...

Identify the name in the list by highlighting it when its content matches the text in a specific div id

I have an unordered list structured like this: <ul> <li id="projectrow_364"> <span>Forest</span> </li> <li id="projectrow_365"> <span>Life</span> ...

Firefox won't trigger the `beforeunload` event unless I interact with the webpage by clicking on it

In my quest to handle the beforeunload event in Firefox, I've encountered a small hurdle. It seems to be working smoothly, but only if the user physically interacts with the page by clicking on it or entering text into an input field. Below is the co ...

Is it possible to update table cell content depending on selected option?

Displayed here is the select block: <form> <select id="select"> <option disabled selected value="choose"> CHOOSE </option> <option value="i2g" id="i ...

Utilize SectionList and a custom header view on Y to achieve a translation effect that creates a visually appealing empty space as

Hello everyone, I am fairly new to React Native and the Animated API. My goal is to create a simple parallax header and an Animated SectionList similar to this demonstration. https://i.stack.imgur.com/R2GBP.gif Below is a snippet of my code: export defa ...

JavaScript - Navigating through JSON object in reverse (from leaf to root) direction

FamilyTree= { "name":"Family", "photo":"images/family.jpg", "members":[ { "name":"Parent", "photo":"images/parent.jpg", "relationships":[ { "name":"Spouse", "photo":"images/spouse.jpg" }, ...

Steps to send an object array using a promise

I've put in a lot of effort but haven't found a solution that works well for me. I attempted using promise.all and setting the array globally, but it didn't work out. My goal is to search through three MongoDB collections, match the finds, ...

Securing special characters in cshtml

I am working on a razor view which includes a hidden field called Model.Token. The Token contains special characters that are then appended to a link in the href attribute. <a href='http://<a href="/cdn-cgi/l/email-protection" class="__cf_email ...

Hiding the style tag in the head section of a Laravel-Vue.js application with Vue.js

Currently, I am working on a Laravel-Vue.js application. I have noticed that when Vue.js renders CSS, it appends some style tags in the HTML head as shown in the image below. Is there a way to hide these tags? My initial thought is that it can be achieved ...

Share JSON data across functions by calling a function

I am currently working on a project where I need to load JSON using a JavaScript function and then make the loaded JSON objects accessible to other functions in the same namespace. However, I have encountered some difficulties in achieving this. Even after ...