Tips for creating brief animations

I am currently working with a moving div in JavaScript that continues to move for a period of time after the key is released. I am looking for a way to immediately stop the animation upon releasing the key.

The animation is controlled by a switch statement using character codes. Can I integrate a keyup function within this switch statement?

 $(".sprite2").hide();

    $(document).keydown(function(key) {
        switch(key.which) {

            // a
            case 65:
                $(".sprite2").hide();
                $(".sprite").show();
                $(".sprite").animate({left: "-=10px"}, 'fast');
                $(".sprite2").animate({left: "-=10px"}, 'fast');
                break;

            // w
            case    87:
                $(".sprite").animate({top: "-=10px"}, 'fast');
                $(".sprite2").animate({top: "-=10px"}, 'fast');
                break;

            // d
            case 68:
                $(".sprite2").show();
                $(".sprite").hide();
                $(".sprite2").animate({left: "+=10px"}, 'fast');
                $(".sprite").animate({left: "+=10px"}, 'fast');
                break;

            // s
            case 83:
                $(".sprite").animate({top: "+=10px"}, 'fast');
                $(".sprite2").animate({top: "+=10px"}, 'fast');
                break;

            case onkeyup: 
                $(".sprite").animate()
        }
    });
}); 

The 'sprite' refers to the HTML element(s).

I encountered issues with the .add/removeClass functions, and resolved it by incorporating a second element and toggling their visibility based on the desired action.

Both elements are identical, but one is mirrored horizontally when moving in the opposite direction to simulate forward movement.

Answer №1

To change the appearance of the div, consider adjusting its CSS properties directly instead of relying on animations. You can update the position by specifying the number of pixels you want it to move relative to its current location upon key press.

Alternatively, here is a demonstration of how to animate movement in different directions based on specific key presses using a switch statement: Check out this JQuery Example

Snippet from the provided link:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8>''
<title>Move an Element Using Arrow Keys with jQuery</title>''
<style type="text/css">'
    .box{
        width: 100px;
        height: 100px;
        position: relative;
        margin: 200px auto 0;
        background: url("../images/mushroom.jpg") yellowgreen;
    }
</style>'
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>'
<script type="text/javascript">'
$(document).keydown(function(e){
    switch (e.which){
    case 37:
        $(".box").finish().animate({
            left: "-=50"
        });
        break;
    case 38:
        $(".box").finish().animate({
            top: "-=50"
        });
        break;
    case 39:
        $(".box").finish().animate({
            left: "+=50"
        });
        break;
    case 40:
        $(".box").finish().animate({
            top: "+=50"
        });
        break;
    }
});
</script>'
</head>
<body>
    <p><strong>Note:</strong> Click inside the output viewport and use arrow keys to move the box.</p>'
    <div class="box"></div>'
</body>'
</html>'

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

Utilizing Cordova and AngularJS to efficiently retrieve JSON data through XMLHttpRequest in a factory

I've encountered an issue while attempting to retrieve a JSON from an API using XMLHttpRequest within a factory. Despite the debug logs suggesting that everything is functioning correctly, I keep getting an "undefined" response. Below is the code for ...

Ensure the presence of a value in an array using Angular

I need to check if any of the "cuesData" have values or lengths greater than 0. However, in my current code, I can only evaluate the first array and not the rest. https://i.sstatic.net/bMpvg.jpg TS checkValues(values) { const result = Object.values ...

What is the best way to optimize my ExpressJS + Sequelize files for proper compatibility with Jest testing framework?

For the past few years, I have been developing an ExpressJS server application for internal use at my workplace. This application serves as a clinical decision support tool utilized in various hospitals. As the application has grown significantly in size, ...

Obtaining serverTime from a webpageWould you like to learn

Is it possible to retrieve the serverTime using jquery ajax functions like $.get() or $.post()? I am looking to store this serverTime in a variable that can be utilized later on in javascript. You can access the webpage at: To use the get and post functi ...

Place the item at the top of the list before scrolling downwards

I'm struggling with what seems like it should be a simple task. My goal is to add new items to the top of a list and have the list scroll down to show the new item. So far, I've managed to create and add a new list item using this code snippet: ...

Utilize Javascript to create a function that organizes numbers in ascending order

Is there a way to modify this code so that the flip clock digits appear in ascending order rather than randomly? $( '.count' ).flip( Math.floor( Math.random() * 10 ) ); setInterval(function(){ $( '.count' ).flip( Math.floor( Math.rand ...

Disabling the global ajax datatype causes issues with Rails remote links

I have successfully developed a rails application that submits a form remotely and then displays form validation errors if the validation process fails. The form itself is working perfectly. However, I've come across an issue where the way I've ...

Maintaining Scene Integrity in THREE.JS: Tips for Handling Window Resizing

My layout includes a div with a scene that looks great initially; however, as soon as I start moving or resizing the window, the scene overflows the boundaries of the div and goes haywire, almost filling the entire window. Are there any techniques or solu ...

Contrasting outcomes when tackling a problem in node.js versus python

After tackling a challenging leetCode problem, I successfully came up with the following solution: Given d dice, each with f faces numbered from 1 to f, determine the number of possible ways (modulo 10^9 + 7) to roll the dice so the sum of the face up nu ...

Using percentages for sizing and margins in CSS

Looking to create a visually appealing page that always fills the entire screen? Check out this code snippet that does just that: #posts{ width:100%; height:auto; background:#666; } .entry{ float:left; margin-left: 4%; margin-top:10 ...

The parseFloat function only considers numbers before the decimal point and disregards

I need my function to properly format a number or string into a decimal number with X amount of digits after the decimal point. The issue I'm facing is that when I pass 3.0004 to my function, it returns 3. After reviewing the documentation, I realized ...

Problems with implementing JavaScript code in a WebView

I am currently working on an android WebView project where I have managed to change the background color to orange with this code snippet. @Override public void onPageFinished(WebView view, String url) { wv.loadUrl("jav ...

Transferring an image between two <td> cells within the same table

For a project, I'm working on creating a Checkers game. I have the checker board and pieces ready, but I'm struggling with the movement logic. My goal is to enable the image to move or transfer from one td element to another when clicked. A frie ...

Determine the total number of hours along with the precise minutes

Could you assist me with calculating minutes? Here is an example: var time_in = '09:15'; var break_out = '12:00'; var break_in = '13:00'; var time_out = '18:00'; var date = '2018-01-31'; var morning = ( ...

How can I effectively set up and utilize distinct npm modules on my local environment?

A React Native component I have created lives in a separate folder with its own package.json file, and now I want to use it in another project. The component named MyComponent is located in Workspace/MyComponent and has specific dependencies listed in its ...

Avoiding redirection in Django template form

Currently, I am facing a challenge with my application that involves rendering a Django Template model form where images are referenced from another model. To manage the addition and deletion of images for this other model, I have implemented a button wit ...

Tips for incorporating an additional dataset bar using chart.js

I'm having a bit of trouble trying to modify the following script. Currently, it only displays one bar per label, but I need it to show 2 bars per label. Despite my numerous attempts using different variations with and without commas and "{}", I can&a ...

Why is my code executing twice rather than just once?

` import './App.css'; import ArrayState from './components/ArrayState'; import FetchApi from './components/FetchAPI/FetchApi'; import Login from './components/Login'; import Useeffect2 from './components/Use ...

JavaScript: Can you clarify the value of this variable using five sets of double quotations?

Could you please review the code snippet below for me? <script type="text/javascript"> function recentpostslist(json) { document.write('<ul class="recommended">'); var i; var j; for (i = 0; i < json.feed.entry.length; i++) { ...

What is the significance of having a timer in a Redux reducer to prompt a re-rendering process?

Encountered some unusual behavior that I need to understand better Here is the code for my reducer. Strangely, the component linked to the redux state does not re-render with this code. Despite confirming through developer tools that the state updates cor ...