The div switches direction once it reaches the border

I am facing an issue with my code. I have a div with the id "ball" that is initially moving towards the top and left. However, when it reaches the top of the wrapper block (with the id "field"), the direction of the ball should change. Unfortunately, the direction changes incorrectly. Below is my code. Please bear with me as I am new to coding and seeking help to resolve this issue.

var ball = document.getElementById('ball');

var timer = setInterval(function ()
{
    var posTop = ball.offsetTop;
    var posLeft = ball.offsetLeft;
    var ballPositionX = parseFloat(window.getComputedStyle(ball).left);
    var ballPositionY = parseFloat(window.getComputedStyle(ball).top);

    ball.style.top = --posTop + 'px';
    ball.style.left = ++posLeft + 'px';

    if (ballPositionX <= 0)
    {
        ball.style.top = --posTop + 'px';
    }
    if (ballPositionX <= 550)
    {
        ball.style.top = ++posTop + 'px';
    }
    if (ballPositionY <= 0)
    {
        ball.style.left = ++posLeft + 'px';
    }
    if (ballPositionY >= 1000)
    {
        ball.style.left = --posLeft + 'px';
    }
}, 10);

HTML:

<div class="field" id="field">
    <div id="here"></div>
    <div class="ball" id="ball"></div>
    <div class="desk" id="desk"></div>
</div>

CSS:

* {
    margin: 0;
    padding: 0;
}

.field {
    margin: 15px auto;
    width: 1000px;
    height: 650px;
    border: 1px solid #000;
    background: aliceblue;
    position: relative;
    overflow: hidden;
}

.ball {
    width: 50px;
    height: 50px;
    -webkit-border-radius: 100px;
    -moz-border-radius: 100px;
    border-radius: 100px;
    background: green;
    -webkit-border: 5px double silver;
    -moz-border: 5px double silver;
    -ms-border: 5px double silver;
    -o-border: 5px double silver;
    border: 5px double silver;
    position: absolute;
    top: 550px;
    left: 0;
}

.desk {
    width: 200px;
    height: 25px;
    background: darkblue;
    -webkit-border: 3px double silver;
    -moz-border: 3px double silver;
    -ms-border: 3px double silver;
    -o-border: 3px double silver;
    border: 3px double silver;
    -webkit-border-radius: 4px;
    -moz-border-radius: 4px;
    border-radius: 4px;
    position: absolute;
    top: 610px;
    left: 10px;
}

.blocks {
    position: absolute;
    left: 0;
    top: 0;
    width: 200px;
    height: 30px;
    background: brown;
    text-align: center;
    color: lightcoral;
}

DEMO: http://jsfiddle.net/n3skLuo3/

Answer №1

Essentially, you must keep track of the direction along the x and y-axes (using two binary flags indicating 'increase/decrease_x/y_coordinate') that need to be adjusted when reflecting off one of the field edges.

var ball  = document.getElementById('ball');
var field = document.getElementById('field');
var d_x = 1.0;
var d_y = 1.0;
var h_ball  = parseFloat(window.getComputedStyle(ball).height);
var w_ball  = parseFloat(window.getComputedStyle(ball).width);
var h_field = parseFloat(window.getComputedStyle(field).height);
var w_field = parseFloat(window.getComputedStyle(field).width);

ball.style.left = '200px';
ball.style.top  = '200px';

var timer = setInterval(function ()
        {
            var posTop  = ball.offsetTop;
            var posLeft = ball.offsetLeft;
            var ballPositionX = parseFloat(window.getComputedStyle(ball). left) ;
            var ballPositionY = parseFloat(window.getComputedStyle(ball). top);

            if ( ballPositionX <= 0 )                 { d_x =  1.0;  }
            if ( ballPositionX >= w_field - w_ball )  { d_x = -1.0; }
            if ( ballPositionY <= 0 )                 { d_y =  1.0;  }
            if ( ballPositionY >= h_field - h_ball )  { d_y = -1.0;  }

            ball.style.top  = (posTop  + d_y) + 'px';
            ball.style.left = (posLeft + d_x) + 'px';
        }, 10);

The d_x/y variables in the code calculate the coordinate change per time step. Adjust their weight and scale based on the coordinates and the magnitude of your velocity vector.

View a live demo on jsFiddle

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

The `pubnub removeListener` function does not get triggered when the `useEffect` hook

Operating a single chat works perfectly; however, upon entering and exiting a chat screen before re-entering it, double messaging occurs, and the listener remains active despite being placed in the return of useEffect. I attempted the solution provided in ...

Sending the id as a prop in react-router-dom

Is it possible to pass an ID in props to a React component using react-router-dom? Take a look at my app.js file below: <Switch location={this.props.location}> <Route exact path="/" component={Home} /> <Route path= ...

JavaScript - Add dropdown menus from choices

Is there a way to automatically generate multiple select lists from a select list, similar to this example: https://i.sstatic.net/D33Jg.png Here is the code I have tried: HTML: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.m ...

What is the Best Way to Achieve the Right Resolution for Your VR Headset?

As I work on developing a WebVR application with three.js, my current focus is on adjusting the window resolution to match the hmd resolution for a clearer visual experience. To gather this information, I have been exploring the use of VREyeParameters re ...

Unexpected jQuery error: Uncaught TypeError - Invocation not allowed

Yesterday, the code was functioning perfectly, but today it suddenly started throwing an error: Uncaught TypeError: Illegal invocation I'm struggling to pinpoint where exactly the issue lies. function createFile() { var selected_retailer_uui ...

Altering the source of an HTML image

I am faced with a situation where I need to change the font color of text under a specific condition using code like this: newEntryRow.find("p").find("span").css('color','red'); Now, my goal is to achieve something similar but by chan ...

"Quotes are essential in Javastript syntax for specifying string values

I need to implement a JavaScript syntax to generate unique URLs for each image. The Robohash website provides random robot images based on different URL endings. I tried the code below, but it seems like ${props.id} is being interpreted as part of the UR ...

Using Angular to send JSON data to an API

I'm attempting to send JSON data to an API, but I'm encountering the following error... 405 (Method Not Allowed) Below is the JSON object I'm trying to send and the corresponding HTTP request... var productAttributes = { "CostRequire ...

Make a request to the local API in a React Native mobile app by sending a GET request

Currently, I am working on a mobile application using React Native and utilizing SQL Server and NodeJS. The API for this project is located in my localhost. Upon running the application on an emulator, I encountered an issue when attempting to make a reque ...

Refresh the view seamlessly using Ajax without reloading the page

When a button is clicked, the following code will run: $.ajax({ type: "POST", url: base_url+"/controller/method", data: {val: value}, success: function(data){ data = jQuery.parseJSON(dat ...

Can you please enlighten me on how to obtain the HTML for the selected area of the cursor in Tiptap?

I've successfully created a customized text editing tool using tiptap/react. My question is, how can I retrieve the html or json of a selected area when I highlight text with the cursor? For instance, if I have a custom tag 'say-as' within ...

How can I design a tooltip window using HTML, jQuery, or other elements to create a box-like effect?

As someone who is new to front end development, I am facing a challenge with my web app. The requirement is that when a user hovers over an image, I need a 'box' to open nearby and display a pie chart. Although I have managed to get the hover fu ...

Managing a variable amount of form input values

One of the challenges I'm facing is handling a form that includes a link to open a modal window for entering additional information. Since this additional information is generated dynamically, I need to find a way to create these items as they are add ...

Using a local variable with jquery getJSON: A comprehensive guide

I am looking to expand the autocomplete capabilities of Ace Editor and I require a JSON file containing words. Here is my code snippet: function load_completions() { var object = $('#preview').attr('class'); $.ajax({ ...

Close popup after submitting the form

On my website, I have a function to submit a form within a modal. Everything works well except for when I uncomment a certain line of code. When I uncomment that line, my test mysql insert on the page /index.php/trainings/add doesn't get executed. I a ...

The NPM Install process seems to be skipping certain files that were successfully installed in the past

When I first installed NPM Install in a folder, it created multiple folders and files: node_modules public src .DS_Store package.json package-lock.json webpack.config.js After that, npm start functioned perfectly. Now, as I embark on a new project for th ...

Nested data selection in React

I have been experimenting with creating a nested select optgroup and attempted the following: const data = [ { sectorId: 5, sectorName: "Sector One", departments: [ { deptName: "Production", jobtitles: [ { ...

Can someone explain the meaning of `$.text(["someText"])`?

I recently stumbled upon a code snippet that I needed to use, and although I managed to implement it, I found myself unsure of its workings. Here is an excerpt from the code: .sortElements(function(a, b){ return $.text([a]) > $.text([b]) ? ...

Tips for accurately dissecting a PDF document to determine the status of checkboxes

Looking for a solution to parse PDF forms on the server side, I have experimented with various node.js modules including pdf2json, hummus, and node-pdftk. While I have successfully retrieved all text fields, I am facing issues when it comes to extracting c ...

Is there a way to enable Tail Recursion Optimization in TypeScript?

const isPositive = (n: number) => n > 0; function fitsIn(dividend: number, divisor: number, count: number, accum: number): number { if (accum + divisor > dividend) { return count; } return ...