Verify whether the object is inside the CSS border or CSS wrapper

As a newcomer to the programming world, I am venturing into my first jQuery project for my ICT school assignment.
Here is an overview of the project:
I have various draggable objects (images) within #wrapper, which is defined in my style.css file.
My goal is to allow these images to change when dragged over a background image that is centrally positioned beneath the wrapper. To achieve this, I am successfully detecting the location of each object:

     drag: function(){
        var who = $("#draggable1");
        var offset1 = who.offset();
        var xPos1 = offset1.left;
        var yPos1 = offset1.top;
        $('#posX').text('x: ' + xPos1);
        $('#posY').text('y: ' + yPos1);

I then determine if the object is within certain X and Y coordinates of the background picture for it to change:

    if(yPos1 > '115' && yPos1 < '578')
            {
            this.src = 'pinkward5.png'
            }

In addition, I have included code to revert the object back to its original position if dropped outside the boundaries of the background image:

    if(xPos1 < '717' || xPos1 > '1202')
            {
            who.animate({ 'top': offset1.top == '0', 'left': offset1.left == '0'}, 200, function(){
            who.stop( true,true );
            who.mouseup();
            this.src = 'visionward.png'
            });

However,
When using a different monitor or adjusting the browser window size, the coordinates change, causing the code not to function as intended due to varying offsets.
My query:
How can I ensure consistent coordinates regardless of screen resolution or browser window size? Perhaps through using percentages or checking whether the object remains within the CSS border of the background image?


Thank you! I hope that I have followed all guidelines outlined by Stack Overflow.

Answer №1

Is hardcoding the coordinates really necessary? You can simply use the "offset()" method on the background image to obtain its coordinates, similar to how you did it for the draggable element, and then calculate the boundaries using its width and height.

var bkgd = $('.whatever-you-name-the-background-image-class');
var bkgd_offset = bkgd.offset();
if(xPos1 >= bkgd_offset.left && xPos1 + who.width() <= bkgd_offset.left + bkgd.width() && 
   yPos1 >= bkgd_offset.top && yPos1 + who.height() <= bkgd_offset.top + bkgd.height())
    /* draggable inside background */;
else
    /* not inside background */;

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

What is the best way to ensure that this header remains adaptable to different screen

Looking for guidance on creating a fluid and responsive header design similar to the curved images shown at this link or this link. How can I ensure that my design maintains its shape without distortion when viewed on different devices? Any suggestions a ...

Tips for Uploading Large Images to Backend API in Next.js

As I work on building my portfolio using NextJS, I encountered an issue with the Project Functionality. When converting images to base64 and sending them to an API for uploading on Cloudinary, everything runs smoothly as long as the total size of the req ...

What is the best way to implement client side validation for a related input field using JavaScript in a Rails application?

Struggling to find a solution for adding a validation check for a dropdown list that is dependent on another input selection in a different form. It seems like database validation may be necessary, but I'm unsure of the best approach. Any suggestions ...

I have noticed that the Javascript code is being loaded prior to the completion of my HTML/CSS page for some unknown

I am completely new to the world of web development. I'm encountering an issue where my JavaScript code (specifically alerts) is loading before my HTML/CSS page has fully loaded. I've been using sample alerts to test this out, and ideally, they s ...

What steps are involved in testing a nextjs endpoint with Jest?

One of my challenges is an endpoint responsible for user sign up: import { createToken } './token'; // Unable to mock import { sendEmail } './email'; // Unable to mock export default async function signUp( req: NextApiRequest, res: ...

Angular 10 does not fulfill promises as expected

In the Angular 10 project I'm working on, I encountered an issue while trying to call an API request asynchronously using promises. The code I wrote didn't seem to execute the API call as expected and kept exiting at the first line without progre ...

Display a featherlightbox popup when the page loads

Well, here's the deal. I don't have any experience with wordpress php coding at all, but I can make basic adjustments using the wordpress admin. Now I've run into an issue. I tried to use the feather lightbox js, and below is a snippet of co ...

Retrieve the user-inputted data from an Electron BrowserView's input field

Consider this scenario where a BrowserWindow is set up with specific security settings, including enabling the webviewTag: true for project requirements. let webPrefs = { plugins: false, nodeIntegration: false, nodeIntegrationInWorker: false, ...

Can a Vue computed property return a promise value?

I have a specific computed property in my code that triggers an API request and retrieves the required data: async ingredients() { const url = "/api/ingredients"; const request = new Request(url, { method: "GET", credentials: "same-or ...

How do I resolve the issue of PHP sendmail form sending empty emails and fix the JavaScript?

I spent the whole day dealing with sendmail.php. Initially, I had an issue with not receiving emails, which I managed to fix. However, after that, I started receiving blank emails. It wasn't a problem with my PHP or HTML code, but rather with the Java ...

What is the best way to conceal the dt tag when the dd tag contains no value

Is there a way to hide the "Subject" if the "subject_title" field is empty? <dt class="col-sm-6 text-dark" >Subject</dt> <dd class="col-sm-6">{{$course_dtl->subject_title }}</dd> For example, I would li ...

Concerns regarding the functionality of form generation using "Recurly.js" alongside GWT and AJAX

Currently, I am in the process of developing a user interface within a GWT application for managing Recurly accounts. This setup eliminates traditional browser navigation when moving between "pages" within the app, allowing the client DOM state to be retai ...

Attempted to execute a Vuex mutation outside of the designated store handler

Within my program, I have designed a form that consists of two checkboxes and a submit button for demonstration purposes. Upon clicking a checkbox, the selection is saved to a variable, which is then pushed to the vuex store when the submit button is click ...

Vue3 is struggling to apply dynamic styling exclusively to certain buttons

Currently, I am diving into the world of vue and facing a challenge in styling buttons dynamically when clicked individually. These buttons serve as filters for a list of products, and my goal is to apply one style when the filter is 'on' and ano ...

Troubleshooting a CSS problem on a table filled with images - See attached screenshots for

I've been working on a project involving my phpmyadmin database generating a series of 6 images on my website. I've placed them in a table, but now I'm facing some challenges - even though it seemed simple at first! The goal is to display t ...

Strange Behavior of SVG 'fill: url(#....)' in Firefox

I am struggling with an SVG graphic that I have created. Here is the code: <svg width='36' height='30'> <defs> <linearGradient id="normal-gradient" x1="0%" y1="0%" x2="0%" y2="100%"> <stop offset="0%" s ...

What is the best way to align content evenly between the logo and navigation items in the Bootstrap navbar?

Welcome to my HTML code: <nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class="container-fluid"> <img class="logo" src="/images/logo.png" alt=""> < ...

What could be causing my inline-block divs to not line up correctly?

Presented below is the code snippet of my HTML: .classWrap { text-align: center; } .classInd { display: inline-block; height: 200px; width: 200px; margin: 20px; border: 2px solid #FFF202; border-radius: 10%; box-shadow: 0 0 15px 0 #FFF2 ...

What is the best way to combine a JSON response object with the variable J inside a for loop?

Received a JSON response as follows: { "name" : "chanchal", "login3" : "1534165718", "login7" : "1534168971", "login6" : "1534168506", "login5" : "1534166215", "login9" : "1534170027", "login2" : "1534148039", "lastname" : "khandelwal", ...

The JSX function seems to be malfunctioning, as the function part is not displaying on the webpage as intended

This code snippet is a part of a React component in a project. I have imported a CSS file for styling and have already integrated Material UI. However, the function for the new article is not displaying on the webpage as expected. import "./Widgets. ...