Preventing internal div movement within the outer div border using JavaScript Animation

Greetings to all the brilliant minds on Stack Overflow!
I have been given a school assignment that requires me to create a basic animation using CSS and JavaScript.
I set up a large outer div and added a smaller div inside it. Using JavaScript, I managed to move the smaller div around the larger one by utilizing the onkeypress event in JS.
However, I am facing an issue that I can't seem to resolve – how do I make the smaller div stop when it reaches the border of the larger div? Currently, in my code, it disappears once it crosses the outer div's boundaries.
Strangely enough, I can't get it to function properly when using the built-in snippet feature on this site. It works flawlessly in WebStorm 11! Any tips or advice would be highly appreciated. Thank you in advance!

< script >
  //Declare Variables
  var test = document.getElementById("test");
var object = document.getElementById("object");
var posx = 200;
var posy = 200;
var width = 100;
var height = 100;
var rotate = 0;
//On KeyDown
document.onkeydown = function keyPress(event) {
    var x = event.which;
    var speed = 5;

    switch (x) {
      case 38:
        test.innerHTML = "Up";
        posy -= speed;
        object.style.top = posy + "px";
        break;
      case 39:
        test.innerHTML = "Right";
        posx += speed;
        object.style.left = posx + "px";
        break;
      case 40:
        test.innerHTML = "Down";
        posy += speed;
        object.style.top = posy + "px";
        break;
      case 37:
         test.innerHTML = “Left”;
         posx -= speed;
         object.style.left = posx + “px”;
         	break;
	      case 90:
        	width += 1;
      	height += 1;
    		test.innerHTML = "Z";
  		  object.style.width = width + "px";
	 	    object.style.height = height + "px";
		 	 break;
	 		 case 88:
        	 test.innerHTML = "X";
	       	 width -= 1;
  	 	    height -= 1;
		 	   object.style.width = width + "px";
		   	   object.style.height = height + "px";
	 		break;
      	 	case 65:
         	rotate += 1;
          	object.style.transform = "rotate('rotate')";

    }

    < /script>
<style> * {
  margin: 0;
  padding: 0;
}
#myDiv {
  background-color: #005f5f;
  width: 500px;
  min-height: 500px;
  position: relative;
  overflow: hidden;
  display: block;
}
#object {
  width: 100px;
  height: 100px;
  background-color: red;
  position: relative;
  top: 200px;
  left: 200px;
  display: block;
}
</style>
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8>
  <title>Lesson #2</title>
</head>

<body>
  <h1>Lesson #2</h1>
  <div id="myDiv>
    <div id="object"> </div>
  </div>
  <div id="test">
  </div>

</body>

</html>

Answer №1

To prevent the object from going off-screen, make sure to include a control statement. If it's an image, set its width to half of the moving object's width in the window. For instance, if you have a 10 pixel dot, adjust 0 to 5 and 200 to 195, and so on.

 < script >
  //Variables Declaration
  var test = document.getElementById("test");
var object = document.getElementById("object");
var posx = 200;
var posy = 200;
var width = 100;
var height = 100;
var rotate = 0;

//KeyDown Event
document.onkeydown = function keyPress(event) {
    var x = event.which;
    var speed = 5;

    switch (x) {
      case 38:
      if(posy > 0){
        test.innerHTML = "Up";      
        posy -= speed;
        object.style.top = posy + "px";
        }
        break;
      case 39:
      if(posx < 200){
        test.innerHTML = "Right";
        posx += speed;
        object.style.left = posx + "px";
        }
        break;
      case 40:
      if(posy < 200){
        test.innerHTML = "Down";
        posy += speed;
        object.style.top = posy + "px";
        }
        break;
      case 37:
      if(posx > 0){
        test.innerHTML = "Left";
        posx -= speed;
        object.style.left = posx + "px";
        }
        break;
      case 90:
        width += 1;
        height += 1;
        test.innerHTML = "Z";
        object.style.width = width + "px";
        object.style.height = height + "px";
        break;
      case 88:
        test.innerHTML = "X";
        width -= 1;
        height -= 1;
        object.style.width = width + "px";
        object.style.height = height + "px";
        break;
      case 65:
        rotate += 1;
        object.style.transform = "rotate('rotate')";

    }

    < /script>

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

Creating a dynamic multi-item carousel with Materialize (CSS) cards using data from a loop - here's how!

Using a for loop, the following code generates a list of cards. These cards are intended to be displayed in a carousel with 4 cards visible at once, and a next arrow button allows users to navigate through the next set of 4 cards. Materialize cards have ...

Turn numerical string into comma-separated format

In my Angular 2 / Typescript project, I am working with a string that contains numeric values such as the ones listed below: 10000 10000.50 -10000 -10000.50 0 I need to insert commas after every thousand mark in these numbers, like so: 10,000 10,00 ...

SlideToggle jQuery Dropdown Menu

$(document).ready(function() { $('.dogs_showall').click(function() { $('.dogs_dropdown li').slideToggle(); }); }); .dogs_dropdown li { display: none; } .dogs_dropdown>li:first-child { display: list-item; } <script src ...

The mystery behind the enigmatic combination of ajax, JQuery,

Seeking Assistance! All fields are displaying undefined values function UpdateData(){ var id = $('#id').attr('value'); var name = $('#name').attr('value'); var department = $('#departament'). ...

Which is faster: looking for a key in an object or searching for a string in an array?

I am in the process of designing a data structure that will be used to frequently check for specific values. I have considered two potential solutions and am currently assessing their efficiency, as well as exploring if there may be better alternatives ava ...

Having trouble locating and scrolling through elements while webscraping with Python Selenium, encountering the 'cannot focus element' error

I have been trying to extract ticket information from the VividSeats website. The URL I am working with is '' My tools of choice are Selenium and Python. I managed to navigate to the page using Chrome WebDriver and interact with the pop-up tha ...

What is the best method to create a grey-colored background using CSS?

I'm curious about how they created the background on the page found at The background is not just a plain color - could it be an image that scales to fit the whole page? Or is there some CSS trickery involved? I noticed in the CSS that the body elem ...

When returning to the page, Vue reactivity experiences a hiccup

Using a basic binary variable called Vue named binary_state, I control the class of an element known as "controlled_element" in this discussion. This "controlled_element" has two classes, "class_true" and "class_false," depending on the value of binary_sta ...

Please explain the concept of the Node.js event loop

I've spent countless hours poring over guides and resources on the event loop, yet I still can't grasp its essence. It's common knowledge that the libuv library is responsible for implementing the event loop, but what exactly is this entity ...

fast-csv has encountered an exception: the column headers do not match the expected values

Currently, I'm using fast-csv to validate data within my code. Here's a snippet of what it looks like: var fileName = req.files.uploadcsv.path; var fs = require("fs"); var stream = fs.createReadStream(fileName); var csv = require("fast-csv"); ...

What is the best way to display numerous images on a cube face while also organizing them like a gallery wall?

I'm working on creating a unique gallery wall using three.js. Currently, I have successfully rendered an image on each side like this: My goal is to place multiple images on each wall instead of just one large image. Something similar to this concept ...

Identify occurrences in the background

In my project, I have implemented FullCalendar with background events using the attribute rendering="background". However, I am facing an issue in detecting when a user clicks on these background events. I have tried the following code snippet but it did ...

Creating an interactive Table of Contents in Sharepoint using only JavaScript

Imagine you have a massive Sharepoint wiki page filled with various heading tags like H1, H2, H3, and H4 - now picture creating a dynamic Table of Contents using these tags. The goal is to categorize these tags by group and utilize the HTML <detail> ...

Identifying Three.js scenes by their names

After 6 hours of diving into Three.js, I am starting to understand new concepts. My current challenge involves accessing objects within a scene that is on a page with two canvases and scenes. Here is the HTML structure I am working with: <div id="my-c ...

Error occurs when implementing Google login in React, happening both during rendering and after successful sign-in

Hey there! I recently started using React-Google-Login to implement a sign-in button on my project. I followed the documentation closely, but unfortunately ran into 2 errors while testing it out. Here's the code snippet I currently have: import Goog ...

Discrepancy between relative path resolving in IE7 and Firefox

Here's the code I have inside my Smarty tpl file (or any simple HTML): <img src="../images/blah.jpg" /> When I view it in Firefox, the path resolves to: localhost/app/index.php/images/blah.jpg (and the image doesn't load). However, in IE7 ...

How can I use jQuery to add animation to the coloring of an SVG graphic?

I want to create a dynamic animation for my SVG using jQuery. I aim to first animate the path of the SVG, and then after the initial animation, I would like to animate the fill of the SVG with specified duration and easing function. Is it possible to achi ...

Basic JavaScript string calculator

I'm in the process of creating a basic JavaScript calculator that prompts the user to input their name and then displays a number based on the input. Each letter in the string will correspond to a value, such as a=1 and b=2. For example, if the user e ...

Establishing the default scroll position in tables using React.js

How can I set the initial scroll in ReactJS Material-UI tables? I'm working with a table that has numerous columns and I would like to have specific columns in view automatically without having to scroll, essentially establishing an initial scroll. I ...

Using Ajax and PHP to Trigger a Forced Download

I am trying to develop a download script that enables the Force Download of JPGs. Below is my PHP script: <?php header("Pragma: public"); // required header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); ...