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

Import failures in Three.js could be attributed to potential issues with Webpack

Please note: I am utilizing create-react-app along with three.js v0.99.0. In my current project, I am faced with the challenge of importing specific modules from three.js to avoid bundling the entire library, which results in a large uncompressed file siz ...

Undefined boolean when passing to AngularJS directive

I developed a custom directive that allows for the addition of a gradient background color in AngularJS: .directive('colouredTile', function () { return { restrict: 'A', controller: 'ColouredTileController&apos ...

What is the reason for the Circle to Polygon node module producing an oval or ellipse shape instead of a circle shape?

I've been experimenting with the npm package circle-to-polygon and I crafted the following code to generate a polygon that resembles a circle. const circleToPolygon = require('circle-to-polygon'); let coordinates = [28.612484207825005, 77. ...

Tips for verifying conditional input fields in a React component?

As a beginner in React, I attempted to create a SignIn form component that dynamically changes its layout based on a boolean prop toggled between Login and Signup options. In the signup version, there is an additional text field labeled Confirm password, w ...

Intersecting objects with Raycaster in three.js

I'm currently working on customizing this particular example from three.js to enable character control via mouse clicks. My objective is to obtain the mouse coordinates upon clicking the canvas and then convert them into 3D space coordinates using THR ...

Steps to alter the color of a JSONLoader-generated object with a simple click

Recently, I've been delving into Three.js and managed to create an object using the JSONLoader. The material of the object is currently grey in color. My goal now is to allow users to change the color of the object by clicking on a button that I have ...

Utilizing React-map-gl in combination with either useContext or useState to update the viewport from a separate component

Lately, I've been struggling to understand how to use useContext and/or useState with React/Nextjs along with react-map-gl. In my project, I have a searchbox component that uses Formik and a map component from react-map-gl. What I'm trying to ach ...

When using `JSON.stringify`, the resulting data may vary from the original object

Here is the code snippet in question: console.log("444444: ", profile, JSON.stringify(profile)) Upon checking the log output: https://i.stack.imgur.com/LzalV.png I am trying to understand why I cannot see the value: [0] present Additionally, ...

Discovering the initial word of a string using jQuery

I'm currently facing an issue with jQuery that I need help solving. Here's the scenario: I am creating tooltips and positioning them directly under a specific trigger using CSS. Everything is functioning correctly, but there is one problem: In ...

Can you explain the significance of "=>" in a context other than function invocation?

Working my way through the freeCodeCamp JavaScript course has left me quite puzzled about arrow functions. I know how to write a function using arrow notation, like this: const myFunc = () => "value"; However, in one of the later challenges, ...

Move router parameters to separate files to streamline and organize code

I have encountered a bit of an issue. I currently have the following code in my routing.js file where I define both my parameter and route. I have moved the routes to a separate router instance in my routing.js file, but I am struggling to separate the par ...

Encountering a Console warning while working with the Material UI menu. Seeking advice on how to resolve this issue as I am integrating HTML within a text

Caution: PropType validation failed. The prop text provided to LinkMenuItem is invalid as it should be a string, not an object. Please review the render method of Menu. Below is the code snippet: var menuItems = [ // text is not valid text { route: &ap ...

What is causing the continuous appearance of null in the console log?

As part of my JavaScript code, I am creating an input element that will be inserted into a div with the id "scripts" in the HTML. Initially, I add a value to this input field using JavaScript, and later I try to retrieve this value in another JavaScript fu ...

Ways to increase the number of rows on datatables while utilizing ajax integration

My issue lies in trying to implement pageLength for my datatables using ajax. Instead of displaying 50 table rows per page as expected, it shows the entire dataset on each page. Here is the code snippet I am working with: JS $('table.dataTableAjax&ap ...

Encountering an issue while attempting to extract an ACF field in WordPress using JavaScript

When I write the following code, everything works fine: <script> $(document).ready(function(){ var user_id = '<?php echo get_current_user_id(); ?>'; // This is working var subject = "<?php echo the_field('subject ...

Iterate over the array and show the elements only when a click event occurs

I am trying to create a loop through an array (array) and display the elements one by one only after clicking a button (bt). However, when I run this code, it only shows the last element of the array (i.e. honda). Can someone please help me fix this issu ...

Choosing read-only text fields using JQuery

I am working on an ASP.NET MVC project and I am looking to select all text boxes with the "readOnly" attribute on the current page. Once identified, I want to trigger a modal jQuery dialog on keypress for each of these disabled text boxes. Any suggestion ...

Generating unique triangle patterns through Webgl

Recently, I began learning webgl and have been attempting to create triangles with random sizes and positions similar to the image below using javascript. I understand that I need to utilize a for loop within the function initScene() but I'm uncertai ...

TestingCompilerFactory is not available as a provider

Currently troubleshooting my test file to identify the issue that is hindering a successful test run: import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { Component, Directive, Input, OnInit } from '@angula ...

Animated the height of a rectangle during initial loading and when the mouse hovers over or leaves

Being new to Vue.js, I am looking to create a simple animation on component load for the first time. You can find my initial code here: <template> <div id="app"> <div class="rect" /> </div> </template ...