Creating a boundary: A step-by-step guide

There is an element that I need help with

<div id="square"></div>

This element has the ability to move around the document

var square = document.getElementById("square");
    document.body.onkeydown = function(e) {
    if (e.keyCode == 37) {left()}
    if (e.keyCode == 38) {up()}
    if (e.keyCode == 39) {right()}
    if (e.keyCode == 40) {down()}
}

How can I create a function that prevents movement if the square element is too close to the document border? JSFiddle: https://jsfiddle.net/zutxyLsq/

Answer №1

In order to ensure that the element stays within boundaries, it's important to check if the position on the left is outside of the boundaries. Here is how you can do this:

function moveLeft() {
    console.log('Moving left');
    var leftPos = parseInt(square.style.left || getComputedStyle(square)['left'], 10);
    if (leftPos >= 50) {
        square.style.left = (leftPos - 50) + 'px';
    }
}

function moveRight() {
    console.log('Moving right');
    var leftPos = parseInt(square.style.left || getComputedStyle(square)['left'], 10);
    if (leftPos + 50 + square.offsetWidth < window.innerWidth) {
        square.style.left = (leftPos + 50) + 'px';
    }
}

For the vertical movements, similar checks can be implemented for up and down directions.

Check out this example 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

Is there a way I can modify the display setting to show 4 slides per view?

var swiper = new Swiper(".new-arrival", { slidesPerView: 4, centeredSlides: false, spaceBetween: 30, autoplay: { delay: 5500, disableOnInteraction: false, }, pagination: { el: ".swiper-pagination", type: &qu ...

Convert your Airbnb short link into the full link

I am currently developing an application that utilizes Airbnb links as part of its input. So far, I have identified two types of links: Long form, for example: . These are commonly used on desktop. Short form, such as: . These shorter links are often shar ...

The method by which JavaScript identifies when a Promise has resolved or rejected

How does JavaScript determine when the state of myPromise has transitioned to "fulfilled" in the code provided below? In other words, what is the process that determines it's time to add the .then() handler to the microqueue for eventual execution? co ...

Leveraging babel-cli on your local machine

Is it possible to utilize the babel client without the need for global installation? Instead of following this method npm install -g babel-cli I am looking to achieve the same outcome by using npm install babel-cli --save-dev ...

Utilizing the {{value}} parameter within the JavaScript block of the thinger.io HTML gadget

When creating an HTML widget with JavaScript code on the thinger.io Dashboard, you can easily include data from the "thing" by using {{value}} within HTML tags. However, incorporating this data into a JavaScript block poses a challenge. Example of a Pure ...

How should one go about creating an npm package out of a vuejs component and testing it locally?

Initially, I created a vuejs project as a test container using vue-cli. Next, I developed an npm package named "vue-npm-example" from a Vuejs component in my local environment and then imported it into the aforementioned testing project. Within the packag ...

Addon for Firefox: Image Upload

I am looking for a way to streamline the process of uploading an image to a website through a Firefox Addon. While I know it is possible to use createElement('canvas'), convert Image data to base64, and XHR POST the data, I would prefer to lever ...

Django and its compatibility with modal windows

I have developed a Django website that includes multiple items in a "for" loop. I need to delete a specific item by opening a modal window and passing the post ID (referred to as "get_post_id") to the modal window. However, I want the modal window to exist ...

Determine the necessary adjustment to center the div on the screen and resize it accordingly

Currently, I am in a situation where I must develop a piece of code that will smoothly enlarge a div from nothing to its final dimensions while simultaneously moving it down from the top of the screen. Each time this action is triggered, the final size of ...

Obtain data in JSON format through an xmlhttp request

I originally used jQuery for this task, but I now want to switch to regular JavaScript as I'll be incorporating it into phonegap. I aim to avoid relying on different JS frameworks every time I make a server request, which could potentially improve per ...

Is there a way to pass attributes to BufferGeometry in THREE.js without using ShaderMaterial?

I've been attempting to make a THREE.js example designed for version 58 compatible with the latest version of THREE.js. You can find the original example here. While I was able to resolve a few errors by simply commenting out certain code, one error ...

Safari displays the contents of JSON files instead of automatically downloading them

I am facing an issue with a JavaScript code that generates a link to download a JSON file. The link is structured like this: <a href="data:text/json;charset=utf-8,..." download="foo.json">download</a> While the link works perfectly in Chrome ...

ReactJS encountered an error: [function] is not defined, July 2017

Attempting to convert a JSON file into an array and then randomly selecting 5 items from it. I suspect the issue lies in my render/return statement at the end of ImageContainer.js, but as a newbie in ReactJS, it could be anything. Any assistance or guida ...

Is it possible to determine whether a path leads to a directory or a file?

Is it possible to distinguish between a file and a directory in a given path? I need to log the directory and file separately, and then convert them into a JSON object. const testFolder = './data/'; fs.readdir(testFolder, (err, files) => { ...

Tips for implementing a delay in jQuery after an event occurs

I am working with text boxes that utilize AJAX to process user input as they type. The issue I'm facing is that the processing event is quite heavy. Is there a way to make the event wait for around 500ms before triggering again? For example, if I type ...

This element is not compatible for use as a JSX component

I have created a React component which looks like this import React from 'react'; import { ECOTileSummary } from './ECOTileSummary'; import { TileSummary } from './TileSummary'; interface SuperTileSummaryProps { date?: s ...

Using JQUERY to execute a callback function after an AJAX request is completed

I encountered a situation where I have the following code snippet: <a onclick="$('.element').hide(0); doMyMethod(_element = $(this));"></a> The doMyMethod() function is actually an ajax request. What I am trying to accomplish is to ...

Choose to either push as a single object or as individual items

I have a quick question that I'd like to get some clarity on. Can someone explain the distinction between these two code snippets: export const addToCart = function(product, quantity){ cart.push({product, quantity}); console.log(`${quantity} ...

Exploring Robotic Arm Actions using three.js

I am currently working on designing a robotic arm with the three.js library. I have a concept in mind to implement hierarchical levels to construct the arm's geometry. The plan is to have the first level of geometry serve as the foundation for all arm ...

Why Isn't the Element Replicating?

I've been working on a simple comment script that allows users to input their name and message, click submit, and have their comment displayed on the page like YouTube. My plan was to use a prebuilt HTML div and clone it for each new comment, adjustin ...