Effortless Basketball Movement Script in Javascript

What happens: Pressing the space button causes the ball to move up and then stop. When pressed again, it moves down.

What I need: I want the ball to move up and then move down when I press the space button!

I'm trying to figure out how to repeat this action twice with just one click. It seems simple enough; I attempted to loop the function twice when the space bar is pressed, but it didn't work as expected. Any suggestions?

var body = document.getElementById('body');
var basketball = document.getElementById('basketball');

var x = 0;
var y = 0;

var counter = 0;
var inc = Math.PI / 100;

body.addEventListener('keydown',function(e){
    var ek = e.which; 
    if(ek==32){
        
            for( var i = 0; i<=1 ;i+=0.01){
                x+=i;
                y+= Math.sin( counter );
                counter+=inc;

                basketball.style.left=x;
                basketball.style.bottom=y; 
            }    
    }
});
* {
    transition: all 1s;
}

#basketball {
    width: 75px;
    position: absolute;
    bottom: 0;
    left: 10;
}
<html>
    <head>                
        <link rel="stylesheet" href="css/index_style.css">        
        <title>Basket</title>
    </head>
    <body id="body">       
        <img src="https://thumbs.dreamstime.com/b/basketball-ball-transparent-checkered-background-realistic-vector-illustration-91566559.jpg" id="basketball">
        
        
        <script src="js/mine.js"></script>
    </body>
</html>

Answer №1

Give this a shot (the function is recursive):

var body = document.getElementById('body');
var basketball = document.getElementById('basketball');

var x = 0;
var y = 0;
var counter = 0;
var inc = Math.PI / 100;

function bounce(e, norecall){
    var ek = e.which; 
    console.log('keydown');
    if(ek==32){
        
        for( var i = 0; i<=1 ;i+=0.01){
            x+=i;
            y+= Math.sin(counter);
            counter+=inc;

            basketball.style.left=x;
            basketball.style.bottom=y; 
        }
            
    }

    if (!norecall) { //only runs the first time (when norecall == undefined)
        bounce(e, true)
    }

}

body.addEventListener('keydown',bounce); //call bounce on keypress
* {
    transition: all 1s;
}

#basketball{
    width: 75px;
    position: absolute;
    bottom: 0;
    left: 10;
}
<html>
    <head>                
        <link rel="stylesheet" href="css/index_style.css">        
        <title>Basket</title>
    </head>
    <body id="body">       
        <img src="https://thumbs.dreamstime.com/b/basketball-ball-transparent-checkered-background-realistic-vector-illustration-91566559.jpg" id="basketball">
        
        
        <script src="js/mine.js"></script>
    </body>
</html>

The functionality of the bounce function involves calling itself with norecall initially set as undefined. When !norecall evaluates to true, the function recursively calls itself with norecall set to true, preventing further function calls and effectively simulating a double mouse press to solve the problem.

Answer №2

Forget about using loops and complex solutions, you can simply leverage CSS by adding a class that adjusts the bottom property, then utilize setTimeout to revert it back after a certain period of time (just make sure to click on the example to give it focus for key events).

var body = document.getElementById('body');
var basketball = document.getElementById('basketball');


body.addEventListener('keydown',function(e){
   basketball.classList.add('up');
   setTimeout(function(){
      basketball.classList.remove('up'); 
   }, 300);
});
#basketball
{
    transition: all 1s;
    width: 75px;
    position: absolute;
    bottom: 0;
    left: 10;
}

#basketball.up {
  bottom: 25px;
}
<html>
    <head>                
        <link rel="stylesheet" href="css/index_style.css">        
        <title>Basket</title>
    </head>
    <body id="body">       
        <img src="https://thumbs.dreamstime.com/b/basketball-ball-transparent-checkered-background-realistic-vector-illustration-91566559.jpg" id="basketball">                        
        <script src="js/mine.js"></script>
    </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

Tips for managing an interval for play, pause, and stop functions in JavaScript or Node.js

In my main file, I have an API to control the playback of a video. main.js const { mainModule } = require('process'); const { startVideo, pauseVideo, stopVideo } = require('./modules/video.js'); function init(payload) { if(payl ...

Using Session Value to Automatically Select Drop Down Box

<select> <?php foreach($result as $city) { ?> <option value="<?php echo $city->city_name; ?>" <?php if( strtolower($this->session->city) == strtolower($city->city_name) ) { echo "selected"; } ?> ...

CSS: Shifting flexbox child to a new row when overflowing

I have a flex row with 2 divs (.box-1 and .box-1) both containing some content. I want them to remain in the same row until the content in .box-1 becomes long enough to push .box-2 to the next line. .box-2 Should have a fixed width on desktop screens. S ...

The loader image does not appear on mobile screens during an AJAX call, but it functions correctly on desktop screens

While I have successfully implemented a loader (.gif) using a div tag in an AJAX call for desktop screens, the same code is not functioning properly on mobile devices. Instead of displaying the loading animation, it simply shows a white screen. <div ...

Step-by-step guide on creating a pressure gauge using canvas

Seeking assistance with creating an animated pressure gauge in Canvas for a new application. I need to animate the red needle to move from one angle to another when given a specific input. My original attempt to calculate the ratio between pressure and ang ...

Styled-Component: Incorporating Variables into Styled-Component is my goal

Currently, I am working on an app and have created a separate file for styling. I decided to use style-components for custom CSS, but faced an issue where I couldn't access variables instead of HEX values. Even after storing color values in a variable ...

Incorrect Date Returned by Sequelize (-1 Day Difference)

My issue revolves around the birthdate field in one of my tables, which has a Data Type of Date. However, when attempting to export the data through an Express app, the date is transformed into a day earlier than it should be. For instance, a birthdate of ...

What is causing the issue with the "Inline-block" property in this CSS code?

Please review the CSS code provided below for styling instructions. /*rex is the container of ex,ex2,ex3*/ div.rex{ height:200px; border:0px; margin:60px auto; padding: 0; vertical-align:top; } div.ex{ width:34%; height:200px; background-color:#4f443a; ...

Filtering with checkboxes (looking for help with logic functionality)

Yesterday, I sought assistance with a similar question and was able to make progress based on the response provided. However, I have encountered another issue that has left me stuck. Current behavior: Clicking on a checkbox changes the background color of ...

Unable to see text scrolling in the div container

I am trying to manipulate a div that contains some phrases: <div class="container"> <div class="phrase-doc">Lorem ipsum bla bla</div> <div class="phrase-doc">Lorem ipsum bla bla</div> <di ...

Tips for creating an Ionic app in Production mode, the Ionic build process may exhibit peculiar behavior

I am in the process of preparing my Ionic application for production. After executing the ionic build --prod command, the application builds successfully. However, upon running it on the server, I encounter errors related to: cordova.js, main.js, Vendor.j ...

Automated line wrapping within a div

My goal is to showcase images within a unique div structure. Currently, the arrangement appears as follows: It seems that the green divs are extending beyond their parent div (the black one). This is how it's structured: <div class="photoView c ...

Unable to access a value from an object in Node.JS/MongoDB platform

I'm seeking assistance with my NodeJs project. The issue I am facing involves checking the seller's name and setting the newOrder.support to match the seller's support internally. Despite logging the correct value within the findOne() func ...

Transfer information from a single form and distribute it across multiple forms with the help of jQuery or Javascript

Form1 has a variety of input fields including text, select, radio, and textarea. At the bottom there is a button labeled "copy" that allows users to copy data from all the fields in Form1. In different pages, I have three to four other forms with input fi ...

Top method in css for removing the corners of a border

I'm working on a video project where I've added text overlay. The design I'm aiming for includes having the corners of the border cut out. To better illustrate, here's an image showcasing what I want to accomplish: Is there a straightf ...

Troubleshooting issue: Next.js Material-ui CSS SSR not functioning properly within components

Upon completing my project, I discovered that SSR for Material-ui is not functioning on the page where I utilized functional components. Here is my _document.js file: [Code from _document.js] Example Page: [Code from E ...

Retrieve progress with easing using jQuery's animate() function

At the moment, I'm utilizing this code to create an animation for a bar-graph-inspired element: $('.anim').animate({ right: `${100-(e/max*100)}%`, backgroundColor: colors[0] },{ duration: 1500, easing: 'easeInQuart&apos ...

Submit form data asynchronously using Ajax and serialize the form data before posting

I'm currently facing an issue with posting HTML form values in my code. Everything works fine except for the fact that I can't get it to post single quotes ' . I believe this problem is caused by the usage of serialize. I've attempted c ...

How can I make angular material data table cells expand to the full width of content that is set to nowrap?

This example demonstrates how the mat-cells are styled with a specific width: .mat-cell { white-space: nowrap; min-width: 150rem; } If the width is not specified, the table will cut off the text due to the white-space property being set to nowrap. Is ...

Can we reduce the number of classes and pseudo classes sharing the same style?

How can I condense the following CSS into a more concise LESS code? .push-nav > .active > a, .push-nav > .active > a:hover, .push-nav > .active > a:focus { background:#000; color: #fff; } Here is my attempt: .push-nav > .act ...