How can I animate an object to stay within the boundaries of a div container?

Recently, I've been working on a fun project where I want to create an image that follows the user's mouse as they navigate the page. Thankfully, I found some helpful information about this on the forums; check out this link for more details: Make an image follow mouse pointer.

However, my main challenge is to restrict the movement of the image within the boundaries of the div it resides in. In other words, I want the image to follow the mouse cursor but not exceed the borders of the div. Despite my efforts to tweak the solution provided in the aforementioned link, I have yet to find success.

(I apologize if this issue appears trivial, as I am still relatively new to coding.)

Answer №1

To ensure the image stays within the boundaries of the div, you can check if the mouse's position is within those boundaries. This means checking if the x position is less than the div's width minus the image's width (to prevent crossing the border) and if the y position is less than the div's height minus the image's height. Keep in mind that this method works effectively when the div is positioned in the top-right corner of the page since the calculations are relative to this corner.

For a practical example, consider the following code:

HTML

<div id="constraint">
    <img id="image" src="http://images.pictureshunt.com/pics/m/mouse-8557.JPG"/>
</div>

CSS

#image{
position:absolute;
}

#constraint {
    height: 400px;
    width: 500px;
    border: 1px solid black;
}

JS

$(document).mousemove(function(e){
    var constraint = $('#constraint');
    var width = constraint.width();  
    var height = constraint.height();  

    var image = $("#image");

    if (e.pageX < width - image.width() && e.pageY < height - image.height()) 
        image.css({left:e.pageX, top:e.pageY});
});

A demonstration based on this concept is available on jsfiddle for your reference: JSFiddle

I trust this explanation clarifies the approach for controlling the image within the div's boundaries.

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

Calculating the total value by summing up all the values in every iteration

After some tinkering, I came up with a function to dynamically adjust the container width based on the combined width of all child sections. It worked like a charm upon initial page load, but unfortunately stumbled when resizing. Check out my code snippet ...

browsing through a timeline created using HTML and CSS

I am currently working on a web project that involves creating a timeline with rows of information, similar to a Gantt chart. Here are the key features I need: The ability for users to scroll horizontally through time. Vertical scrolling capability to na ...

Tips on creating a React Vite Typescript website that utilizes the entire height and ensures a minimum width

I'm currently working on building a portfolio webpage with React, Vite, and Typescript, but I'm facing an issue where the content is not taking up the full height of the page. I have multiple pages with different lengths of content that I want to ...

Employ Ajax for updating a database using a Select option instead of a form with a button

My goal is to utilize ajax in order to select an option and store the data in a database, rather than using a select within a form along with a button. This approach is necessary because I have one select for each row, and every time I change the selected ...

Trouble aligning items in a fieldset with Bootstrap

While working on a wire frame, I am attempting to create the HTML structure based on it. The required structure that needs to be built is outlined in this diagram: https://i.sstatic.net/ypp2f.png Progress has been made on aligning elements using a two-col ...

The jQuery Cookie is failing to be set with every click as expected

I am currently working on a layout switcher feature. When a user clicks on a specific div with the class name display, it triggers the toggling of another class called display-grid for visual enhancements. This functionality also involves switching classe ...

A step-by-step guide to triggering a click event using CSS

This code snippet is working as expected: .rightone ul { list-style: none; padding: 0px; margin: 0px; } .rightone ul li { display: block; position: relative; float:right; } .rightone li ul { display: none; } .rightone ul li a ...

The issue of receiving a 400 (Bad Request) error when making an ajax post call with an array to a Spring

My database schema includes a OneToMany mapping defined as follows: @Entity public class Foo implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long ...

The MouseEnter and MouseLeave events are not being properly queued

I'm encountering an issue with a drop-down animation in my navigation menu. The sub-menus show or hide based on user hover, but when users quickly move over the element, the menu ends up staying open. Despite trying to use the .stop(true) function al ...

Modify the original source data of an HTML table

I have written the following code: <table class="table table-hover"> <thead> <tr> <th>Status</th> <th>MPK</th> <th>Full Name</th> <th>Phone Number</th> <th>Proj ...

Unable to send a PHP array to jQuery

Struggling to transfer PHP-encoded array to JavaScript. homepage.php echo '<script src="script.js"></script>'; $a=array(1,2,3,4,5); echo json_encode($a); ?> script.js: $.ajax({ method: 'GET', url: 'index ...

Is there a way to prevent the text next to these FontAwesome icons from moving whenever the icon itself changes?

I am currently working on creating a unique custom checkmark using FontAwesome in my project. Below is the snippet of HTML and CSS style code that I am using: .check { font-size: 1.25rem; cursor: pointer; } .check-unselected { color: #4E44 ...

Can someone please explain to me why the Transition effect is not functioning properly for input:checked::before?

Can someone please help me troubleshoot why the transition effect on the input's before element is not working when checked? If I can't solve this issue, I might have to consider alternative solutions. input[type="checkbox"]{ width: 160px ...

Tips for aligning one item in the center and another item on the right with MUI v5

My goal is to center 3 navigation tabs in the middle of my page and have a dropdown on the far right for sorting. I managed to get the dropdown on the far right, but I'm having trouble perfectly centering the 3 navigation tabs inside the <Box> & ...

Utilizing JQuery and Jade to extract and display information from a Node.js server

I am currently working with the Jade framework for frontend and using Node.js & express for backend development. When rendering a view with data, I am encountering an issue where I can't access this data using JQuery. Below is my service in Node.js ...

The second jQueryUI datepicker instance flickers and vanishes when the show() function is triggered

I currently have two jQueryUI datepickers integrated into my webpage. The initialization code for both is as follows: jQuery("#departureDate").datepicker({ beforeShow: function() { getDatesForCalendar("outbound"); }, numberOfMonths: 3 ...

Are your macOS devices not displaying the Scrollbar CSS buttons correctly?

I need help troubleshooting why my buttons are not appearing in the scrollbar on macOS. They function properly on Windows, so I suspect there may be a typo or error in my code. Can anyone take a look and provide some insight? ::-webkit-scrollbar { wid ...

Embed the WordPress header file outside of the WordPress platform

Recently diving into the world of WordPress, I am eager to integrate the WordPress header file into my PHP file in order to display the identical header as seen on the WordPress site. I am exploring potential methods to achieve this as I work on creating ...

Issue with JQuery's parentsUntil method when using an element as a variable not producing the desired results

I'm having trouble with a specific coding issue that can be best illustrated through examples: For example, this code snippet works as expected: $(startContainer).parents().each(function(index, parentNode) { if (parentNode.isSameNode(commonConta ...

Ways to acquire ttf files from a third-party domain without encountering CORS issues

I am attempting to obtain a .ttf file from an external website for use in my web application. However, when I try the following code: @font-face { font-family: 'font'; src: url('http://xxx.xyz/resources/tipografias/font.ttf') forma ...