Changing the background of one div by dragging and dropping a colored div using jQuery

Looking at my HTML code, I have 4 <div> elements - 2 represent doors and 2 represent colors based on their respective id attributes.

My goal is to enable users to drag any color to either door (e.g. blue on the left door and black on the right) and have the background color change dynamically.

<div id="door1" style="background: #fff;"></div>
<div id="door2" style="background: #fff;"></div>
<div id="black"></div>
<div id="blue"></div>

I would greatly appreciate any guidance or direction that can be provided to achieve this functionality.

Answer №1

To start, make sure to set up your color <div>'s as draggable and door <div>'s as droppable widgets by using the methods .draggable() and .droppable() respectively.

Next, utilize the drop event handler of the droppable to change the background color. In this handler, you can refer to the droppable element using this and the dragged element using ui.draggable as demonstrated below:

$(".color").draggable({
  revert:true
});
$(".door").droppable({
  drop: function(e, ui) {
    console.log(ui.draggable)
    $(this).css("background-color", ui.draggable.attr("id"));
  }
});
.door {
  display: inline-block;
  width: 50px;
  height: 120px;
  border: 1px solid;
  margin: 5px;
}
.color {
  float: right;
  width: 50px;
  height: 50px;
}
.white {
  background: #fff;
}
#black {
  background: #000;
}
#blue {
  clear: left;
  background: royalblue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.min.js"></script>
<div id="door1" class="door white"></div>
<div id="door2" class="door white"></div>
<div id="black" class="color"></div>
<div id="blue" class="color"></div>


Just a side note: I have eliminated the inline css and opted for css classes to streamline your styles and maintain cleanliness in your HTML structure. For more information, you can explore Why Use CSS @ MDN

Answer №2

When the "draggable" stops moving, identify the specific div that was targeted (retrieve the 'left' and 'top' attributes of the dragged div) and color it with the same color as the div that was dragged.

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

Tips for properly implementing a bcrypt comparison within a promise?

Previously, my code was functioning correctly. However, it now seems to be broken for some unknown reason. I am using MariaDB as my database and attempting to compare passwords. Unfortunately, I keep encountering an error that says "Unexpected Identifier o ...

Error: Your request could not be processed due to a Bad

url = "/IPM/KPI/Add"; input = new FormData($('#frmKPI').get(0)) ; PostAjax: function (isForm, url, input, divErrID, btnID, isSuccessFunction, isFailedFunction, NoModalAlert, isAsync) { var contentType = isForm ? false : "appli ...

The hover effect on MUI TableRows is being overshadowed by the background color of the TableCell

I'm currently using @mui/material version ^5.10.1. My challenge is applying the TableRow hover behavior as outlined in the documentation. However, I have also set a background color for the first TableCell in each row, which ends up overriding the ho ...

"Enhancing webpage dynamics with jQuery: Exploring the

I have a beginner's question regarding my jQuery script. The script I have makes the menu move slightly to the right. My first issue is that the <a> tag seems to be receiving bottom padding, and I am unsure why or how this is happening. My secon ...

My ejs page is not showing up because a variable has not been defined

I am facing an issue with an undefined variable causing my EJS page to not display properly when an if statement is included. Removing the if statement allows the page to render, but the presence of the undefined variable and if statement triggers an error ...

I am experiencing technical difficulties with my API resulting in a 500 Internal Server Error

My application involves managing products using CRUD operations. I am able to successfully make an HTTP request to the /api/deleteProduct route in order to delete a product based on its ID. However, the issue lies with creating a new product as the functi ...

Submitting data to a PHP script using AJAX and the $_POST method

I'm attempting to transfer data from my AJAX request into a PHP $_POST variable in order to update my database. HTML <form id="23" method="post"> <select name="admin" onchange="chosenadmin(23)"> <option value="rick">rick&l ...

Exploring the possibilities of integrating a new checkbox feature using jQuery's ajax functionality

After receiving an ajax result, a new element has been added to the page. The checkbox in question is: <input type="checkbox" checked="checked" uid="933518636168122368" class="flag"> How can I select this checkbox? Despite my efforts, my code doe ...

Mastering the syntax of Babel in Node.js

Hey there! I've encountered a syntax issue while migrating to babel. The problem lies in importing an unnamed module. In traditional Node.js default import, it's possible to import without specifying the module name and passing in the app. Howeve ...

Issue with Slider Width in WP 5.6 editor and ACF Pro causing layout problems

Is anyone else experiencing a specific issue after updating to WP 5.6? Since the update, all my websites are facing problems with rendering a Slick Slider in the Block Editor. Interestingly, everything looks fine on the front-end. The root of the problem ...

"Executing ng-click directive on a second click changes the route in AngularJS

Why does my ng-click only redirect to a new location on the second click? It should redirect to $location.path('/login.signin');, but it only works if I click the button again. It's strange. Where could this issue be originating from? Belo ...

Creating inner borders on a pie chart with HTML and CSS: A step-by-step guide

After putting my coding skills to the test, I successfully crafted a stunning pie chart using only HTML and CSS. https://i.sstatic.net/5xCbl.png Here's the code snippet I tinkered with: HTML - <div class="pie-chart"></div> CS ...

What is the method for initiating a radial gradient from the middle of the pie chart?

In my pie chart with grid lines, I have successfully implemented a radial gradient. However, the issue is that there is a separate gradient for each pie slice. What I really want is a single gradient originating from the center of the entire pie chart. I ...

Change the border color of radio buttons when clicked

When one of the radio buttons is clicked, it should give an outer border with color. When the other radio button is clicked, it should give an inner border that surrounds the image. <!DOCTYPE html> <html> <head> ...

Struggling to destructure props when using getStaticProps in NextJS?

I have been working on an app using Next JS and typescript. My goal is to fetch data from an api using getStaticProps, and then destructure the returned props. Unfortunately, I am facing some issues with de-structuring the props. Below is my getStaticProp ...

Attempting to send a filled array to res.render, but struggling to implement a suitable async callback mechanism

I am facing a challenge in creating a function that retrieves a list of IPs from a database, collects server information based on those IPs, stores the data in objects, and finally adds these objects to an array. While I can successfully populate each obje ...

My jQuery DataTables iDisplayLength seems to be malfunctioning. Any tips on resolving this issue?

Currently, I am faced with an issue when trying to retrieve a large amount of data from a MySQL database. To prevent overloading the server, I have set a specific display length for the jQuery Datatable options. However, it seems that despite my efforts to ...

Creating numerous Facebook posts using jQuery technology

I am currently facing a challenge when attempting to publish multiple facebook posts on a webpage using jQuery. Although I have managed to successfully post the first facebook post, I am encountering difficulties when trying to post another one. What coul ...

Try implementing jQuery to switch out an href link

Is there a way to replace a specific link using jQuery without impacting other links in the navigation menu? <ul class="navigation" <li class="level0 nav-1 level-top first parent"> <a href="mylink.com/whats-new.html" class="level- ...

Incorporate jQuery UI Datepicker with the ability to trigger an Ajax function upon selecting a

Is it possible to execute Ajax on date select from a datepicker and how can I handle it? I am not receiving any errors in the console regarding the Ajax part. Instead of getting the pro-rated subscription value, I am seeing "success" in the div with ID &ap ...