Revert animation back to its initial position with the help of JavaScript

After implementing the script below, I successfully managed to shift my image to the right upon clicking:

<script>
var myTimer = null;

function move(){
    document.getElementById("fish").style.left = 
        parseInt(document.getElementById("fish").style.left)+1+'px';
}


window.onload=function(){

    document.getElementById("fish").onclick=function(){
        if(myTimer == null){
            myTimer = setInterval("move();", 10);
        }else{
            clearInterval(myTimer);
            myTimer = null;
        }
    }
}
</script>

I am facing difficulty in reverting the picture to its original position without relying on jQuery.

Your assistance with this matter would be greatly appreciated.

Answer №1

To store the initial position in advance allows for resetting it back to that value later:

let initialPos = document.getElementById("fish").style.left;

function revertPosition() {
    document.getElementById("fish").style.left = initialPos;
}

Answer №2

Implementing external JavaScript is crucial for efficiently managing code:

var previousOnload = onload, element, documentObj, bodyElement;
onload = function(){
if(previousOnload) previousOnload();

documentObj = document; 
bodyElement = documentObj.body;

element = function(id){
  return documentObj.getElementById(id);
}

var fishElement = element('fish'), timerObject;

fishElement.onclick = function(){
  if(!timerObject){
    timerObject = setInterval(function(){
      fishElement.style.left = parseInt(fishElement.style.left)+1+'px';
    }, 10);
  } else {
    clearInterval(timerObject); timerObject = false;
    fishElement.style.left = '0'; // please update with your CSS `left:`value
  }

}// end of onload function

Answer №3

Everything seems to be in order here,



    
    let timer = null;
    let startPosition = 0;

    function swim(){
        document.getElementById("fish").style.left = 
            parseInt(document.getElementById("fish").style.left) + 1 + 'px';
    }


    window.onload=function(){

        document.getElementById("fish").onclick=function(){
            if(timer == null){
                startPosition = document.getElementById("fish").style.left;
                timer = setInterval("swim();", 10);
            }else{
                clearInterval(timer);
                timer = null;
                document.getElementById("fish").style.left = startPosition + "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

Issue with React: Reading the 'pathname' property from undefined is not possible

I can't figure out why this error keeps popping up. My goal is to create animated transitions between Routes. Can anyone point out where I went wrong? view image description here I tried reinstalling the react-spring package but it didn't solve t ...

Why do I keep receiving values only from the initial form? What could be the issue?

I am facing an issue on my website with multiple forms. The problem arises when the "Save" button is clicked, as it continues to check the fields in the first form instead of the form where the button is located. Here is a snippet of my current Ajax scrip ...

"Encountering a puzzling issue with Django Rest Framework where the path setup is functioning for one link but not for

I'm currently attempting to connect to my MySQL database using the Django REST backend. On my frontend, I'm using Vue with Axios. Specifically, I have a junction table called TeacherSubjectJunction, and I want to access it through the following p ...

Audio Playlists and Dynamic Loading with WordPress Shortcode

I'm looking to incorporate the wp_audio_shortcode() function using AJAX, and then customize the style of the audio player. However, I'm facing an issue where the HTML code returned by the AJAX request does not allow me to customize the audio play ...

Discover a technique to display every individual "echo" statement from PHP in sequence, rather than waiting for the entire script to finish executing

I have developed a PHP script that takes some time to execute and displays multiple "echo" statements as the progress is being made. The script connects to an FTP server, deletes all contents, and then uploads new files. Everything is functioning correctly ...

What is a way to adjust the width of fixed columns in a Bootstrap 4.0 responsive table?

I've been struggling to make this work despite following similar questions and answers. I attempted to adjust the column width by directly setting each one, but nothing seems to change! <thead style="white-space: nowrap"> ...

Encountering a 401 error message with a 'truncated server' response while using Google Apps Script

I'm currently working on a code snippet that looks like this. function method3() { var spreadsheetID = '1BGi80ZBoChrMXGOyCbu2pn0ptIL6uve2ib62gV-db_o'; var sheetName = 'Form Responses 1'; var queryColumnLetterStart = ...

Transmit information from the frontend to the backend using JavaScript and the Express framework

After creating a custom variable in my frontend to store data, I needed to access the same data in my Express backend. The JavaScript variable and the POST request code snippet are as follows: const dataPush = { urlSave: urlSave, ...

Step-by-step guide to start an AngularJs application using TypeScript

I have developed an AngularJS App using TypeScript The main app where I initialize the App: module MainApp { export class App { public static Module : ng.IModule = angular.module("mainApp", []) } } And my controller: module MainApp { exp ...

Retrieve the route from a specific node in the jstree structure

Looking to retrieve the paths of selected nodes in jstree? You'll need the complete path of the nodes. I have a php file that generates the JSON, structured like this: header("Content-Type: application/json; charset=utf8"); echo json_encode(dir_to_ ...

Create dynamic cells for CSS grid using JavaScript

I have been manually generating grid cells in a specific pattern by copying and adjusting <div> elements. Although this method works, I am interested in creating an algorithm that can automatically generate the desired layout. The left box in the exa ...

Using ReactJS and react-router to exclude the navigation menu on the login page

I have a LoginPage designed like this: https://i.sstatic.net/yzovV.png After logging in, you will be directed to this page: https://i.sstatic.net/pZFou.png Now, I want the login page to have no navigation and look like this: https://i.sstatic.net/1sH9v ...

Alter the onSeries property dynamically

If there are 3 different series identified by the IDs series1, series2, and flags, where initially the onSeries property of flags is set to series1. In a scenario where I click on the legend to hide series1, is it possible within the legendItemClick even ...

Adding EventListeners for Click Handling: A Step-by-Step Guide

Here is the part of my code in HTML: <!DOCTYPE html> <html> <head> <h> <title> This page</title> </h> </head> <body> <button id = "go-button" >GO ...

Traverse JSON object as a string

I'm new to working with JavaScript. I have a JSON string that was created using the Google Gson API, and I'm passing this string to a JavaScript function. The JSON string looks like this: '{"validationCode":"V10291","caseNumber":"2010CF1010 ...

What's the best way to showcase data in a column dynamically depending on its specific columns?

I have an array of objects representing columns and another array representing table data. I need to dynamically display the data in the specified columns. Some objects have 3 key-values which should be displayed in specific columns. The second object in ...

Having trouble getting my local website to load the CSS stylesheet through Express and Node.js in my browser

https://i.stack.imgur.com/qpsQI.png https://i.stack.imgur.com/l3wAJ.png Here is the app.js screenshot: https://i.stack.imgur.com/l3wAJ.png I have experimented with different combinations of href and express.static(""); addresses. However, I am ...

JavaScript - Declaring canvas as a global object

Presently, I am experimenting with HTML5 and using JavaScript to create a basic 2D Tile map. Progress is going smoothly; however, I have come across an issue where I am unable to contain everything within one large function. I am attempting to make the ca ...

Utilizing Angular routing in HTML5 mode within a Node.js environment

While I've come across other solutions to this problem, they all seem to have drawbacks. One option leads to a redirect, which could be disastrous for my front-end application that relies on Mixpanel. A double-load of Mixpanel results in a Maximum Ca ...

Add axios requests to the axios.all array

Good evening. I am currently trying to insert an array into the axios.all([]) structure! This is the code snippet I am working on: app2.js new Vue({ el: '#central', data: { estilo: 'resize:none;text-align:center;color: ...