Alter the background color based on the movement of the mouse

Is it possible to dynamically change the background color of elements on a webpage based on mouse coordinates?

Current setup:

I have a draggable DIV-A and several droppable divs on the page.

What I am looking for:

I want to highlight the droppable divs whenever my DIV-A is dragged over them. I have access to the mouse coordinates, so I'm wondering if it's feasible to use jQuery to apply CSS changes to these elements based on the position of the mouse.

Answer №1

One possible solution involves dealing with window scroll movements to achieve the desired effect. Implementing throttle and memoize functions may also be necessary for optimizing performance, especially if drop positions remain constant.

To further enhance performance, consider caching the offset values, binding mousemove events only when required, and utilizing an optimized loop structure within the each function.

It's important to note that this script will change the color of div elements only when the mouse cursor passes over them, not necessarily when a draggable item intersects. This complexity can be addressed by refining the provided function below:

$(document).mousemove(function(e){
     // Ensure throttling is implemented...
     var x = e.pageX,
         y = e.pageY;
     
     $("div.droppables").each(function(){
         // Memoization could improve efficiency here...
         var self = $(this),
             divL = self.offset().left,
             divT = self.offset().top,
             divR = self.width() + divL,
             divB = self.height() + divT;

         if(x >= divL && x <= divR && y >= divT && y <= divB){
              self.css("background", "red");
         }
         else{
              self.css("background", "");   
         }
     });
});

Answer №2

Here is a demonstration that I have posted for you to view. The demo showcases the cycling through each droppable position, highlighting that with numerous positions, it may result in slower mouse movement.

In addition, I have included two adjustable variables - xmargin and ymargin - which can be modified to increase or decrease the proximity to the droppable area.

CSS

.draggable { width: 100px; height: 100px; padding: 0.5em; position: absolute; top: 0; left: 0; z-index: 2; }
.droppable { width: 150px; height: 150px; padding: 0.5em; position: absolute; z-index: 1; }
#drop1 { top: 200px; left: 250px; }
#drop2 { top: 450px; left: 50px; }

HTML

<div class="draggable ui-widget-content">
  <p>Drag me towards my target</p>
</div>

<div id="drop1" class="droppable ui-widget-header">
  <p>Drop objects here</p>
</div>

<div id="drop2" class="droppable ui-widget-header">
  <p>Place items here</p>
</div>

Script

$(function(){
 var xmargin = 15,
  ymargin = 15,
  drag = $('.draggable'),
  drop = $('.droppable'),
  dgw = drag.outerWidth() + xmargin,
  dgh = drag.outerHeight() + ymargin,
  pos = [];

 drop
  .droppable({
   //hoverClass: 'ui-state-active',
   drop: function(event, ui) {
    $(this).addClass('ui-state-highlight').find('p').html('Object Dropped!');
   }
  })
  // set up coordinates array (left, top, right, bottom) for each droppable element
  .each(function(i){
    var dropzone = drop.eq(i);
    var l = dropzone.position().left,
     t = dropzone.position().top,
     r = l + dropzone.outerWidth() + xmargin,
     b = t + dropzone.outerHeight() + ymargin;
   pos.push([l,t,r,b]);
  });

 drag
  .draggable()
  .bind( "drag", function(event,ui){
   var l = ui.offset.left,
       t = ui.offset.top;
  
   drop.each(function(i){
    if ( ( l + dgw ) > pos[i][0] && l < pos[i][2] && ( t + dgh ) > pos[i][1] && t < pos[i][3] ) {
     $(this).addClass('ui-state-active');
    } else {
     $(this).removeClass('ui-state-active');
    }
   });
  });

});

Answer №3

Check out the "Interactive demonstration" example on jQuery UI. As indicated by user123, the absence of IDs is inconsequential if you employ a class for selection purposes. Apologies if my interpretation is inaccurate.

Answer №4

Define selector and selector2 as per your requirements...

$(selector).mousemove(function(event) {

   // Establish boundaries, these values are arbitrary and depend on the specific area you are targeting...
   var minX= 0,
       maxX = 150,
       minY = 50,
       maxY = 200,
       currentX = event.pageX,
       currentY = event.pageY;

   var bgColor = currentX > minX && currentX < maxX && currentY > minY && currentY < maxY ? 'blue' : 'yellow';

   $(selector2).css('background-color', bgColor);
});

Answer №5

To achieve this effect, utilize the .hover() function to modify the background color of a div when the mouse hovers over it:

$("specificdiv").hover(function () {
    $(this).css("background-color", "#00ff00");
  },
  function () {
    $(this).css("background-color", "#000000");
});

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

Fancybox's Exciting Tandem Events

I am currently experiencing an issue with my popup ajax contact form as it only has one close event... The AJAX contact form I have consists of two buttons, SEND and CANCEL. When I click the SEND button, the Sweet Alert confirmation message displays ...

Sorry, but we are experiencing difficulties processing your request at the moment. HTTP ERROR 500: We are unable to locate the

My code seems to be functioning correctly when connecting to the database, but I'm encountering an error. Here is the code snippet: <?php include 'header.php'; ?> <!DOCTYPE html> <html> <head> <t ...

Toggle between FlyControls and OrbitControls in ThreeJS when the mouse is clicked

I had been using something similar to this: How to switch between TrackBall and FlyControls in three.js? However, when I try to switch from FlyControls to OrbitControls, the rotation feature becomes unresponsive after clicking to rotate. It seems like th ...

Is it possible to use AJAX in JavaScript to dynamically update page titles?

When loading a new page using AJAX, I am having trouble updating the title. The expected titles should be "Home", "About", and "FAQ". I attempted to solve this by changing the title with the code snippet below, but it only resulted in displaying "undefine ...

Checking the format of a postal code or zipcode using a regular expression

My goal is to validate zip codes or pin codes in address fields. As a result, I am working on writing a regular expression that only allows characters a-z (upper and lower case), digits 0-9, round brackets (e.g. ()), hyphens -, and spaces. However, there a ...

Using jQuery to dynamically disable a textbox when a checkbox is checked

I'm trying to implement a functionality where a textbox becomes disabled and changes its background color when a user unchecks a checkbox. Conversely, if the user checks the checkbox, the textbox should become editable and change its background color ...

The output from a spawned process behaves oddly when it is being piped

I have a goal to convert the session of a process execution into JSON (similar to [{ type: 'stdout', data: 'What's your name?' }, { type: 'stdin', data: 'Alex.' }, { type: 'stdout', data: 'Hi, Ale ...

unemployed with XMLHttpRequest not functioning

I have exhausted all recommended solutions for similar issues, yet this simple code refuses to work. My goal is to retrieve a message from the PHP code in the same file using XMLHttpRequest. <!DOCTYPE html> <head></head> <body> < ...

The error message from Object.create() indicates that the argument provided is not recognized as

Description Within my project, I am handling a JSON file, parsing it into an object, and attempting to transform it into an instance of the ProjectFile class using Object.create(). Code let tmpFileContent = fs.readFileSync(tmpPath, {encoding: 'utf- ...

Ways to perform a force click on a span element when clicking on a glyphicon

There is a table cell containing two span elements: <span contentEditable=true class="editspan"></span> <span class="pencilspan glyphicon glyphicon-pencil pull-right"></span>" When clicking on span1, an input box appears for editi ...

Displaying a relative div on mouse hover over an HTML tag using React

In the section below, you will find the code snippet... <ul className="no-style board__list"> {Object.keys(today.books).map(function(id) { var refBook = today.books[id][0]; return ( ...

Identifying Angular 2 templates post-file separation: a step-by-step guide

I am currently trying to figure out how to initiate a project in Angular 2 and have encountered an issue. Following the steps outlined in this Angular 2 guide, I was able to separate my .ts files from .js files by configuring my 'temp' directory ...

Executing PHP code upon the successful completion of a jQuery Ajax request

How can I assign a value to a PHP variable after a successful ajax call? header.php <script> j.ajax({ method: 'get', url: '/php/ajax/auto_select_market.php', data: { 'city': geoi ...

What is a regex with a touch of greed in its capture

I am considering the following options: ' !This is a string! ' '!This is a string !' '! This is a string !' ' ! This is a string! ' ' ! This is a string ' For each of these scenarios, I aim to find ...

Experiencing difficulties typing into a text/input field using electron

I am currently working on a calendar app using electron. In the app, I have created a menu to add new events and other features. One feature I want to implement is allowing users to enter the title of their event in a textbox/input field. However, when I t ...

The 3D Circle Flip feature on a certain webpage designed by Nordstrom is experiencing issues when viewed on Firefox

Click here to see a 3D Circle Flip effect. It works correctly in Chrome, but in Firefox the text does not change when flipping. ...

Two divisions inside another "wrapper" division - Adjusting the width

I'm facing an issue with my CSS. I have a container div "container" that contains two other divs - "left" and "main". The width of the container is set to 90% of the body's width, with a margin of 3% auto to center it. .container{ margin:3% auto ...

What are the components found within literal entities?

Here is an example of HTML code: <div id='myDiv'></div> If I try to hide the 'myDiv' element using the following JavaScript, it doesn't work: var test = { vars: { $mydiv: $('#myDiv') }, ...

Encountering issues with uploading Cloudinary images through Nodejs

I'm having trouble uploading a base64encoded image to Cloudinary using the code snippet below. It's not working as expected and I keep getting a 500 error when making the post request. Can anyone provide me with a solution or suggest what might b ...

"Exploring the concept of undefined within object-oriented programming and its role in

Recently diving into Express and trying out routing by creating an object in a file to export. import userController from "../controllers/userController.js" // get all users router.get("/", isAuth, isAdmin, userController.list) Encoun ...