How to retrieve an object once it exits the viewport in JavaScript

I am seeking guidance on how to reset an object to its initial position (0) once it exits the browser window. Currently, I have an image that moves when you click on the up/down/left/right buttons, but it eventually extends beyond the browser window.

Below is the code snippet I am currently working with:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8>             
       <style>
            img {
                position: absolute;
                top: 500px;
                left: 100px;
            }

            .buttons {
                background-color: aliceblue;
                margin: 0 auto;
                display: flex;
                justify-content: center;
            }
        </style>
        <script type="text/javascript">
            function moveBall(direction) {

                var moveDistance = parseInt(document.getElementById('box').value);

                var currentTop = parseInt(document.getElementById('ball').getBoundingClientRect().top);
                var currentLeft = parseInt(document.getElementById('ball').getBoundingClientRect().left);

                switch (direction){

                    case 'up':
                        var newTop = currentTop - moveDistance;
                        var newTopString = newTop + "px";
                        document.getElementById('ball').style.top = newTopString;
                        break;
                    case 'right':
                        var newRight = currentLeft + moveDistance;
                        var newRightString = newRight + "px";
                        document.getElementById('ball').style.left = newRightString;
                        break;
                    case 'down':
                        var newDown = currentTop + moveDistance;
                        var newDownString = newDown + "px";
                        document.getElementById('ball').style.top = newDownString;
                        break;
                    case 'left':
                        var newLeft = currentLeft - moveDistance;
                        var newLeftString = newLeft + "px";
                        document.getElementById('ball').style.left = newLeftString;
                        break;
                }
            }
        </script>
    </head>
    <body>
        <img src="images/ball.png" alt="Ball" id="ball" width="100px" height="100px">
        <div class="buttons">
            <input id="box" type="number">
            <button id="up" onClick="moveBall('up')">Up</button>
            <button id="right" onClick="moveBall('right')">Right</button>
            <button id="down" onClick="moveBall('down')">Down</button>
            <button id="left" onClick="moveBall('left')">Left</button>
        </div>
    </body>
</html>

I believe utilizing innerWidth and innerHeight might help in achieving this, but I need some assistance in implementing it.

Answer №1

let 
    screenHeight = document.body.clientHeight,
    screenWidth = document.body.clientWidth;

By utilizing the code above, you can access the width of the bounding rectangle. If you happen to move outside of it, simply reset the position of the ball back to 0.

if (newRight > screenWidth) newRight = 0;

Additionally, consider customizing this functionality based on whether you prefer the entire ball exiting the bounds, its center going beyond, or just touching the edge before resetting.

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

I encountered a validation error and a 404 error while trying to input data into all fields. Kindly review and check for accuracy. Additionally, I have included an

click here for image description Despite providing all details in the form fields, I keep receiving an error message prompting me to enter all fields... I am also encountering a "/api/user 404 Not Found" error and unsure of the reason. Interestingly, wh ...

Execute another Ajax request using jQuery after the first Ajax callback has been completed

Looking for a solution to ensure the correct order of appended contents loaded via ajax, I have the following script: $.get('http://mydomain.com/ajax1.php/', function(data){ var data_one = $(data).find('#ajax_editor_suggestion_c ...

Using specific delimiters in Vue.js components when integrating with Django and Vue-loader

While working on my Django + Vue.js v3 app, I came across a helpful tool called vue3-sfc-loader. This allows me to easily render .vue files using Django, giving me the best of both worlds. The current setup allows Django to successfully render the .vue fil ...

Leverage regular expressions to extract numbers preceding the final matched instance

Within my string of logs, I have the following: rgb(255, 255, 255) 0px 0px 0px 16px inset I am interested in extracting the dynamic value, which in this case is 16. How can I create a regex pattern that will capture the last instance of px, and then retr ...

JavaScript hovering drop-down feature

Hi there, I'm just starting out with javascript and could use some help with a simple script. I have a shopping cart drop down that currently activates when clicked. However, I want it to fade in when hovered over instead. I've tried using .hove ...

Creating multiple AJAX contact forms can be achieved by modifying the code to accommodate multiple forms on a single page. Here's

My one-page website features 15 identical contact forms all with the same ID, created using basic PHP. Unfortunately, I am facing an issue where AJAX is only working for the first form. When submitting any other form, it simply opens a white page with a "T ...

javascript to retrieve data by reducing

Here is the code snippet I am working with: var points = 4; var yModifier = []; for (var i = 0; i <= points; i++) { yModifier.push([]); }; yModifier.forEach( (a, j) => { var start = j; var end = start + points; fo ...

Tips for resolving the React Hook Type Error issue

Error Image const isLoggedIn = true; const handleChangeEvent = () => {}; const [displayPassword, setDisplayPassword] = useState(false); const handleTogglePassword = () => setDisplayPassword((prevDisplayPassword) => !prevDi ...

What is the best way to instantiate objects, arrays, and object-arrays in an Angular service class?

How can I nest an object within another object and then include it in an array of objects inside an Angular service class? I need to enable two-way binding in my form, so I must pass a variable from the service class to the HTML template. trainer.service. ...

Arranging Material UI tabs on both sides

I'm currently working with Material UI tabs and I'm trying to achieve a layout where some tabs are positioned to the left and others to the right. For instance, if I have 5 tabs, I want 3 on the left and 2 on the right. I've tried placing th ...

What is the standard approach for exchanging localized user interface strings between Microsoft's MVC and JavaScript?

In the process of developing an application that utilizes a dynamic, javascript-based client, I am facing the need for localization. This particular application includes significant UI components that are not generated by Javascript and are instead served ...

ReactJS - Continuous Loop invoking Encapsulated Function

I keep encountering the same issue with an infinite loop in my code, but I can't figure out why. Currently, I am working with reactJS version 16.5.2 The infinite loops tend to occur when you try to use SetState where it is not allowed (such as in th ...

What is the best way to expand the width of a table cell in a React + Material project?

Currently, I am utilizing material UI in conjunction with React to display my data in a table format. Within the table, there are specific titles such as "GENERAL_INFORMATION" and "INFORMATION" that I intend to center align. However, I have encountered an ...

React code is displaying as plain text and the components are not being rendered properly

My latest creation is a component named "componentRepeater" with the main purpose of displaying multiple instances of child components. The props within the "componentRepeater" include properties for the child components, the number of repeats for the chil ...

Implement the Vue.js @click directive in a location outside of an HTML element

I've set up a link like this: <a href="#" @click="modal=true">Open modal</a> Here's the data setup: export default { data () { return { modal: false } } } Is there a way to trigger the cli ...

AngularJS $http.get request failing to retrieve data

I've been delving into AngularJS lately, but I'm having trouble displaying the data from my MySQL database on the view. Here's the code snippets I'm working with: todoController.js angular .module('todoApp') .control ...

How to control Formik inputs from an external source

I'm currently developing an application with speech-to-text commands functionality. I have created a form, but I am looking to manipulate the input elements from outside the form framework. <form id="myform"> <input type="tex ...

Unleashing the Power of the "OR" Operator in Form Field Validation

The custom JavaScript function FormQuote_Validator is used to validate form fields. It should return the value "TRUE" and display an alert message if all three input fields are submitted without any numbers; otherwise, it should return the value "FALSE". ...

Node/Express: The $ symbol is failing to recognize the input for PORT 8080

What steps should I follow to run my PORT on 8080? Is it necessary to install any dependencies? const app = require('express')(); const PORT = 8080; app.listen( PORT, () => console.log('It's now running on http://localhost:$ ...

Removing a Dom element using stage.removeChild( )

When the number 6 is typed and entered into the game, the function correct() in the code snippet below determines what action to take. I would like to remove the DOM element gg (the equation 3+3=input) from the stage after typing 6 and pressing enter. How ...