Tips for containing a moving element within the boundaries of its container div

I have a dynamic box placed inside another box, and I want to restrict its movement within the boundaries of the parent container. How can I achieve this?

In simpler terms: I need the frog to stay within the frogger.

HTML

<div id="frogger">                          <!-- Animate start -->
  <button id="left">&laquo;</button> <button id="right">&raquo;</button>
    <div id="frog">
    </div>
</div>                                      <!-- Animate end -->

CSS

#frogger
{
    width: 500px;
    height: 500px;
    border: solid;
    margin: 0 auto;
}

#frog
{
  position:relative;
  background-color:#abc;
  left:50px;
  width:90px;
  height:90px;
  margin:5px;
}

Javascript

$("#right").click(function(){
    if ($(':animated').length) {
        return false;
    } else {
        $("#frog").animate({"left": "+=50px"}, {queue: false}, "slow");
    }   
});

$("#left").click(function(){
    if ($(':animated').length) {
        return false;
    } else {
        $("#frog").animate({"left": "-=50px"}, {queue: false}, "slow");
    }
});

Answer №1

To prevent the frog from moving too close to the edge, you can check its current position before allowing it to move:

var $frog = $("#frog");

$("#right").click(function(){
    if (parseInt($frog.css('left')) >= 400 || $(':animated').length) {
        return false;
    } else {
        $frog.animate({"left": "+=50px"}, {queue: false}, "slow");
    }   
});

$("#left").click(function(){

    if (parseInt($frog.css('left')) < 50 || $(':animated').length) {
        return false;
    } else {
        $frog.animate({"left": "-=50px"}, {queue: false}, "slow");
    }
});

Check out the demo here: http://jsfiddle.net/n3NgY/

If you want to make this code more robust, you can dynamically calculate the width of the frog and its container instead of hardcoding the boundary numbers.

Answer №2

Doing simple collision detection requires a bit more than just CSS. You can achieve this dynamically by following these steps:

$("#right").click(function(){
    var playerRight = $("#player").offset().left + $("#player").width();
    var obstacleRight = $("#obstacle").offset().left + $("#obstacle").width();

    if ($(':animated').length || playerRight >= obstacleRight) {
        return false;
    } else {
        $("#player").animate({"left": "+=50px"}, {queue: false}, "slow");
    }   
});

$("#left").click(function(){
    var playerLeft = $("#player").offset().left;
    var obstacleLeft = $("#obstacle").offset().left;

    if ($(':animated').length || playerLeft <= obstacleLeft) {
        return false;
    } else {
        $("#player").animate({"left": "-=50px"}, {queue: false}, "slow");
    }
});

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

In Internet Explorer 8, the PNG image is visible but in IE7, it myster

I have been trying to showcase a logo (PNG created in Paint.NET) on my website (XHTML 1.0 Transitional), using the following code: <body> <div class="header"> <div class="logo"> <img src="logo.png" /> </div> ...

"Exploring the Depths: How Node.js Utilizes Recursive Calls

I need assistance generating a comprehensive list of all users' flairs on a specific subreddit. To achieve this, Reddit breaks down the requests into chunks of 1,000 and offers both "before" and "after" parameters for fetching purposes. However, I am ...

Include onload to element without running it in Puppeteer

I am currently developing a web scraping tool using Puppeteer. Once the webpage is fully loaded, I need to update the HTML code and include an onload event for certain elements. The issue is that in Puppeteer, the onload event is actually triggered automa ...

Unable to execute an Angular 2 application within Visual Studio 2015

I encountered an error while trying to set up an environment on VS 2015 with Angular2. Whenever I run the command "npm start," I receive the following error message. I attempted using "npm cache clean --force" before running "npm start," but the error pers ...

What is the best way to append data to the end of an object using ReactJS Hooks?

Looking to set up a checkbox page in ReactJS where data is filtered by checkboxes from different categories using ReactJS hooks. Currently, I am storing the selected checkboxes as an object: { color: 'orange', shape: 'square' } ...

Having trouble with installing the most recent versions of React App dependencies

After cloning a project from GitHub, I attempted to install dependencies using npm install, but encountered an error: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email ...

What is the conventional method for incorporating style elements into Vue.js components?

Imagine I have a Vue component with data retrieved from an external API, containing information about various books: data: () => ({ books: [ {name: 'The Voyage of the Beagle', author: 'Charles Darwin'}, {name: &ap ...

Nest JS Guards - Employ either of two approaches

I have implemented two different JWT based strategies in my application: The first strategy involves single sign-on for organization members, where an external provider generates a JWT. The second strategy is for email/password authenticated external user ...

Steps for Renewing Firebase Session Cookie

I am currently developing a web application utilizing Node.js/Express.js for the backend, with Firebase being used for user authentication. To manage user registration and other tasks, I rely on the Firebase Admin SDK. When a user attempts to log in, the ...

Determining the availability of a remote source in React: A step-by-step guide

Is there a way to verify the existence of a remote resource, such as a large zip file, without actually downloading the file? What is the most efficient method for checking the presence of the resource? ...

Prevent the page from refreshing when a value is entered

I currently have a table embedded within an HTML form that serves multiple purposes. The first column in the table displays data retrieved from a web server, while the second column allows for modifying the values before submitting them back to the server. ...

What is the best way to establish a maximum limit for a counter within an onclick event?

I'm struggling to figure out how to set a maximum limit for a counter in my onclick event. Can someone help me? What is the best way to add a max limit to the counter of an onclick event? Do I need to use an if statement? If yes, how should it be w ...

Eliminate duplicate objects from arrays of objects by a specific key name

Here are some arrays of objects I am working with: var arr = [ {name: 'john', last: 'smith'}, {name: 'jane', last: 'doe'}, {name: 'johnny', last: 'appleseed'}, {name: 'johnson', ...

Deactivating the class from a button

On my website, I have 3 buttons that represent different product categories. The initial state of the page should load with the "All Products" button having an active class. However, when clicked, this active class should be removed from the "All Products" ...

Exploring the Possibilities of Wordpress Search with Multiple Dropdown Options

Is it possible to search across multiple categories? For example, I have 4 dropdown menus: 1. City 2. Area 3. Month 4. Products/Services When a user visits my site, they will see a static page with 4 dropdown lists and a "search" button. After the user ...

What is the reason for Vue not updating the component after the Pinia state is modified (when deleting an object from an Array)?

When using my deleteHandler function in pinia, I noticed an issue where the users array was not being re-rendered even though the state changed in vue devtools. Interestingly, if I modify values within the array instead of deleting an object from it, Vue ...

Choosing the appropriate data type for form data on the server

Seeking assistance on uploading an audio file to my server using the following method: var fd = new FormData(); fd.append('fname', 'test.wav'); fd.append('data', soundBlob); $.ajax({ type: 'POST', url: &apos ...

Leveraging jQuery within Node.js

Greetings, I am a newcomer here and I hope that my message is clear. My current challenge involves trying to incorporate jQuery into node.js, but unfortunately, all my efforts have ended in failure. I have spent hours attempting to resolve this issue to no ...

After closing the box, make sure to hold it securely

After clicking the button and closing my box with jQuery (Toggle), I want the state of the box to be remembered after refreshing the page. If the box was closed, it should remain closed upon refresh, and if it was open, it should stay open. I am looking ...