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

Swap out internal Wordpress hyperlinks for Next.js Link Component

Currently, I am working on a project where I'm using WordPress as a headless CMS with GraphQL for my Next.js app. Most aspects are running smoothly except for the internal content links within articles that are fetched through the WP API. These links ...

Retrieving the contents of a unique 404 error page using ajax

Currently attempting to retrieve the content of a custom 404 page through ajax (I need to extract a counter value from this page using Greasemonkey). Regrettably, jQuery's .fail method in ajax does not provide the option to access the page's con ...

Running an express server on localhost with nginx: A step-by-step guide

Is it possible to run the express server using Nginx on localhost? And if so, how can this be accomplished? const express = require('express') const app = express() const port = 3000 app.get('/', (req, res) => res.send('Hello ...

The Angular @HostListener beforeunload Event is a powerful way to handle

I've implemented the following code snippet in my main app.component.ts file within my Angular 17 project: @HostListener("window:beforeunload", ["$event"]) onTabClose($event: BeforeUnloadEvent) { $event.preventDefault(); ...

Leveraging Github CI for TypeScript and Jest Testing

My attempts to replicate my local setup into Github CI are not successful. Even simple commands like ls are not working as expected. However, the installation of TypeScript and Jest appears to be successful locally. During the Github CI run, I see a list ...

Cross-Origin Request Sharing (CORS) problem encountered while making an API call with

My current challenge involves calling an API that returns data in XML format as a response. While testing the .htm file on my local machine, I encountered the following error. https://i.stack.imgur.com/FsvZ0.png Similarly, running it from the codepen.io ...

Issues with Angular2 causing function to not run as expected

After clicking a button to trigger createPlaylist(), the function fails to execute asd(). I attempted combining everything into one function, but still encountered the same issue. The console.log(resp) statement never logs anything. What could be causing ...

Ways to verify the presence of an item in a MonoDB array

My MongoDB model looks like this: const userSchema = new Schema = ({ name: { type: String }, company: [ companyId: { type: String, }, movies: [ { genre: { type: String, enum: [ ...

Alert: React-Weather is causing an invalid element type in React

I am feeling overwhelmed. I have created a custom component called react-weather which has been installed using npm. Here is the code snippet for my self-written Weather.js component located in the src/components folder: import React, { Component } from & ...

Is it possible to manipulate a modal within a controller by utilizing a certain attribute in HTML, based on specific conditions (without relying on any bootstrap services), using AngularJS?

Within my application, I have a modal that is triggered by clicking on a button (ng-click) based on certain conditions. Here is the HTML code: <button type="button" class="btn btn-outlined" ng-click="vm.change()" data-modal-target="#add-save-all-alert ...

When utilizing JqGrid, make sure to utilize the 'aftersavefunc' and 'successfunc' methods prior to executing the 'saveRow' function

After saving a row in order to retrieve the Id for logging, I am encountering an issue where 'aftersavefunc' and 'successfunc' are triggering 'reloadGrid('#telephoneGrid')' before the save operation. It seems that th ...

Step-by-step guide to implementing a sticky header while scrolling

How can I implement a fixed header on scroll, like the one seen on this website: www.avauntmagazine.com Here is the HTML for my header: <div class="bloc bgc-wild-blue-yonder l-bloc " id="bloc-1"> <div class="container bloc-sm"> &l ...

Adjust CardMedia Images to match their content in the new MUI 5 version

I’m looking to have my images fully fill the CardMedia component. However, because they are of varying sizes, some end up being cropped like this: https://i.stack.imgur.com/JHIrT.png Additionally, when resizing the images, some get cut off as well: ht ...

What is the best way to combine PHP and HTML within a JavaScript script?

I'm facing a challenge with integrating dynamically added elements and a populated drop down on my form. Is there a way to combine the two seamlessly? Below is the code snippet I'm using for dynamically adding and removing elements: $(docu ...

The modal window pops up immediately upon the first click

Experience a dynamic modal element that springs to life with just the click of a button or an image. The magic lies in the combination of HTML, CSS, and jQuery code: <div id="modal-1" class="modal"> <div class="button modal-button" data-butto ...

The instance of my ObjectType is coming back as an empty entity

Having trouble making relationships between two object types in my code. One of them is working fine, but the other one returns an empty object and I can't seem to find the issue. The first one works as expected and logs the rank type without any pro ...

Update the user information quickly

In my Express application, I have implemented several routes and a login function. Each user has a balance associated with their data, which is stored in an 'express-session'. However, when the user refreshes the page, I need the balance to be up ...

Utilize the JavaScript .send function to pass an array

Can an array be passed to a PHP page using the code below? If not, what modifications are needed in the code? function ajax_post(){ var hr = new XMLHttpRequest(); hr.open("POST", "get_numbers.php", true); hr.setRequestHeader("Content-type", "a ...

Implement a callback function for unchecked checkboxes on change

Currently, I am working with a gridview that includes a checkbox field. My goal is to use jQuery to create a function that activates when an unchecked checkbox is checked. function clickAllSize() { alert("helloy"); } $(document).ready(function () { ...

The synergy between HTML and JavaScript: A beginner's guide to frontend coding

I have primarily focused on server-side development of enterprise applications (Java EE, Spring framework). However, I am now exploring client-side technologies for better understanding (not necessarily to become an expert). I have studied HTML and CSS th ...