"Enhanced Web Interactions with JavaScript Animations

I've been diving into my JavaScript project lately. I'm currently focusing on creating some cool animations, particularly one that involves making a ball bounce up and down. My code seems to work flawlessly for the downward bounce, but I'm facing some challenges with the upward bounce.

var div = document.getElementById('container-ball');

function createBall(event)
{
    var x = event.clientX;
    var y = event.clientY; 
    var newBall = document.createElement('div');
    newBall.style.position = "absolute"
    newBall.style.width = '15px';
    newBall.style.height = '15px';
    var bx = newBall.style.left = x + 'px';
    var by = newBall.style.top = y + 'px';
    newBall.style.borderRadius = '10px';
    newBall.style.backgroundColor = 'white';
    var incrementPos = 0;
    var id = setInterval(bounce, 5);


    function bounce() 
    {
        incrementPos++;
        by = newBall.style.top = incrementPos + y + "px";
    
        if(by == 650 + "px")
        {
            clearInterval(id);
            var id2 = setInterval(function bounceUp()
            {
                incrementPosYMax -= 650;
                by = newBall.style.bottom = by + "px" - incrementPosYMax;
            }, 5);
        }/*Function that make the ball bounce down and up(but when it came at 650 px it stopped )*/
    } /*End of the set interval */
    div.appendChild(newBall);
}
div.addEventListener("click", createBall);

Below is the corresponding HTML CODE

<html>
<head>
    <link rel= "stylesheet" href="style/style.css">
</head>

<body>

    <div id ="container-ball">
        
    </div>

    <script src="js/main.js"></script>
</body>

Answer №1

Below is a functioning example (with additional comments):

const areaHeight = 150; // originally 650px in height

var div = document.getElementById('container-ball');

function createBall(event) {
  var x = event.clientX;
  var y = event.clientY;
  var newBall = document.createElement('div');
  newBall.className = 'ball';
  var bx = newBall.style.left = x + 'px';
  var by = newBall.style.top = y + 'px';
  var incrementPos = 0;
  var id = setInterval(bounce, 5);

  let direction = 1; // 1 = down, -1 = up

  function bounce() {
    incrementPos += direction;
    by = newBall.style.top = incrementPos + y + "px";

    if (by == areaHeight + "px" || by == y + 'px') {
      direction = -direction;
    }
  }
  
  div.appendChild(newBall);
}
#container-ball {
  width: 300px;
  height: 157px;
  background: gray;
}

#container-ball .ball {
  position: absolute;
  width: 15px;
  height: 15px;
  border-radius: 10px;
  background-color: white;
  border: 1px solid #333;
  box-sizing: border-box;
}
<div id="container-ball" onclick="createBall(event)"></div>
Click on the grey box

Here is the explanation:

  1. The ball's styles are now controlled by CSS for easier management in the future. The class for the ball is assigned using newBall.className = 'ball';
  2. The incrementPosYMax variable was removed as its purpose was unclear
  3. The ball behavior was interpreted as a simple bounce to the floor and back to its original position
  4. Only one setInterval function is used for the animation as the program is small
  5. A direction variable was added to control the ball's movement direction (1 = down, -1 = up)
  6. Existing code for handling the ball's position boundaries were preserved
  7. Any bugs in the code can be addressed once the correct approach is confirmed

Explanation of the movement direction:

  1. The line
    by = newBall.style.top = incrementPos + y + "px";
    updates the ball's vertical position based on the sum of the original y coordinate and the incremental position value
  2. In the original code, the offset was increased by 1 on each bounce step with incrementPos++;
  3. To change direction, 1 must be subtracted on each bounce step
  4. The direction is controlled by the direction variable (1 for down, -1 for up)
  5. The offset is updated using incrementPos += direction; to incorporate the direction
  6. Direction changes occur with direction = -direction;
  7. The boundaries for direction changes are checked using
    if (by == areaHeight + "px" || by == y + '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

Adjusting the opacity of images in a Bootstrap 4 Jumbotron without affecting the text

Is there a way to apply an opacity of 0.5 to only the background image in my jumbotron, without affecting the text? Currently, when I set the opacity for the background, it also affects the text. How can this be resolved? Below is the custom CSS file: .j ...

Getting the Value from a Promise into a Variable in a React Component

I am currently immersed in a React project where I am utilizing the Axios library to retrieve data from an API and store it in a variable. After scouring the internet, it seems that the only method available is through Promise.then(), but this approach si ...

How to retrieve video duration in Angular 2 before uploading the file

Is there a way to retrieve the video duration before uploading it in Angular2? I am looking for a solution without using jQuery. Here is the code snippet I have so far: <input type="file" class="form-control" ng2FileSelect [uploader]="uploader" accept= ...

Error encountered when attempting to retrieve data from a JSON object

I'm in the process of extracting some information from a JSON object, but I've encountered a confusing issue. The JSON object structure is as follows: { "status": "success", "data": { "image": null, "video": null, "author": null, "publisher": "M ...

HTML: Organize a slightly intricate column in a table

I am facing an issue with sorting columns in an HTML table that has 2 headers row: <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="styles.css"> </head> <body> <table ...

"Keep a new tab open at all times, even when submitting a form in

I have a form with two submit buttons - one to open the page in a new tab (preview) and another for regular form submission (publish). The issues I am facing are: When I click the preview button to open in a new tab, if I then click the publish button a ...

Challenge encountered while creating a child tag that can be assigned to multiple parent tags

I have an xml format like the one provided. <xml> <parent id="0"> <child type="name"> </child> <child type="age"> </child> </parent> <parent id="1"> <ch ...

Issue with Bootstrap 5 navbar dropdown: It opens easily but struggles to close

I am currently using Bootstrap 5 to design a website and have incorporated a dropdown feature into the navigation bar. On desktop, when hovering over the dropdown, it should open, while on mobile, clicking the dropdown should toggle its visibility (open/cl ...

Issue with custom font display malfunction

I'm having difficulty getting my custom @font-face to function properly. When I apply this class style to a <p>, it always defaults to Arial. Can anyone point out what might be going wrong here? <style> .stonefont @font-face { font-fa ...

The donut chart in Chart.js is stuck in grayscale without any colorization

I just set up a donut chart using chart.js with the following code: <div id="chartContainer" style="height: 320px; width: 320px"> <canvas id="hoursFEContainer"></canvas> </div> To use chart.js, I downlo ...

Press the button in an HTML document to activate JavaScript

What could be the issue with my code? I have a button in HTML <a class="btn btn-warning btn-mini publish-btn" href="#" data-rowid="@computer.id" data-toggle="modal" data-target="#myModal">Outdated</a> and my modal <fieldset style="text-al ...

Assign a unique identifier to the Angular mat-checkbox component

I need to attach an ID to an Angular material checkbox. I have an object called item. When I check the HTML code, it shows 'item.id + '-input'. However, when I bind the name, it works fine with just 'item.id'. Below is my current ...

Is it possible to use "/path/{?}" in a path when working with Node.js?

I am new to node.js and I'm working on creating a route that will verify the authorization of all users when the specified endpoint begins with /api. I've learned that an optional value can be indicated using ? like {_id?}, but is it possible to ...

The ability to choose only one option in a checkbox within a grid view column

In my grid view, I have a checkbox in the last column. I am trying to ensure that only one row can be selected at a time. <tr *ngFor="let permit of PermitDetails" (click)="GoByClick(permit)"> <td style="text-align: center">{{permit.TVA_BAT ...

Setting the default value for a dropdown in Angular 2 using Kendo UI

I'm currently facing an issue with creating a dropdownlist using Kendo UI. The problem arises when I try to set a default selected value upon loading the screen. Referring to their documentation, my code is structured like this: HTML: <kendo-drop ...

Get the source of a nested iframe inside a parent iframe

On one of my web pages, I have an iFrame that displays the content of another page with its own embedded iFrame. Unfortunately, I do not have control over this external page. I am wondering if there is a way to extract the src attribute of the nested iFram ...

Searching through a JSON object on a Laravel web page using JavaScript or AJAX for live filtering purposes

After diving into AJAX and JavaScript, I find myself needing to replace some outdated Angular functionality on our Laravel site. The specific task at hand is creating a live search filter for a page with a static header search bar. The main requirement is ...

Creating a fully responsive HTML page with a fullscreen image background

Seeking help from someone who can assist me. I have a challenge in creating a webpage with a background image that fills its <div>. Here is the code I used: <style type="text/css> .myclassdiv { background-image:url('IMAGEURL') ...

Border shifts on hover effect

After much trial and error, I finally managed to center two links in a nav bar perfectly on the page. I also added a grey bottom border that spans the entire width of the page, with the hover effect turning it blue under the links. Check out this example: ...

Error: Unable to access the 'CustomerId' property because it is undefined

Recently, I made some updates to my website. As part of the upgrade process, I switched to AngularJS v1.7.6 and JQuery v1.12.1. However, after making these changes, I encountered an error in my console log. TypeError: Cannot read property 'CustomerId ...