Unable to disable background color for droppable element

For my project, I am working with two div boxes. My goal is to make it so that when I drag and drop box002 into another div box001, the background color of box001 should change to none.

I have attempted to achieve this functionality using jQuery without success. How can I accomplish this task using JavaScript?

In my code, I have set up functions for allowing the drop event, handling the drag event, and executing the drop action. However, I am struggling with changing the background color dynamically.

function allowDrop(ev){
  ev.preventDefault();
}

function drag(ev){
  ev.dataTransfer.setData("Text", ev.target.id);
}

function drop(ev){
  ev.preventDefault();

  var data = ev.dataTransfer.getData("Text");

  var el = document.getElementById(data);

  el.parentNode.removeChild(el);
}
.box001 {
  float: left;
  width: 150px;
  height: 150px;
  border: 1px solid black;
  border-radius: 10%;
  background-color: #42e0fd;
}

.box002 {
  float: left;
  width: 50px;
  height: 50px;
  margin: -50px;
  right: 20px;
  float: left;
  bottom: 0;
  left: 0;
  margin-bottom: 20px;
}
<div class="box001" ondrop="drop(event)" ondragover="allowDrop(event)" id="10" style="background-color: #42e0fd;">
  <p>8:30</p>
</div>

<div class="box002" draggable="true" ondragstart="drag(event)">
  <img src="https://picsum.photos/200/300" draggable="true" id="1" style="width:50px; height:50px; border-radius: 50%;" border="rounded" />
</div>

Answer №1

  1. When addressing your question, utilize the following code snippet within the drop function:

    document.getElementsByClassName('box001')[0].style.backgroundColor = 'initial';


2. When attempting to style with CSS using className, ensure you use .className{} in CSS with a preceding ..

Review the code snippet and some CSS modifications below:

    function allowDrop(ev){
      ev.preventDefault();
    }

    function drag(ev){
      ev.dataTransfer.setData("Text", ev.target.id);
    }

    function drop(ev){
      ev.preventDefault();

      var data = ev.dataTransfer.getData("Text");

      var el = document.getElementById(data);

      el.parentNode.removeChild(el);
     document.getElementsByClassName('box001')[0].style.backgroundColor = 'initial';
    }
    .box001 {
      float: left;
      width: 150px;
      height: 150px;
      border: 1px solid black;
      border-radius: 10%;
      background-color: #42e0fd;
    }

    .box002 {
    width: 50px;
    height: 50px;
    margin: -50px;
    top: 76px;
    float: left;
    position: absolute;
    left: 217px;
    }
<div class="box001" ondrop="drop(event)" ondragover="allowDrop(event)" id="10" style="background-color: #42e0fd;">
        <p>8:30</p>
    </div>

    <div class="box002" draggable="true" ondragstart="drag(event)">
        <img src="https://picsum.photos/200/300" draggable="true" id="1" style="width:50px; height:50px; border-radius: 50%;" border="rounded" />
    </div>

Answer №2

Within the drop feature, perform an action similar to this:

document.querySelector('.container001').style.background = 'clear';

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

A guide on serializing multiple objects returned from a loop using JSON.stringify

My MVC code involves adding multiple travelers objects to the travelers array generated in a loop, and then using JSON.stringify on them. return amadeus.booking.flightOrders.post( JSON.stringify({ 'data':{ 'type ...

Using jQuery, implement a functionality where a line break is added when the Enter key is pressed. Furthermore, the added

I have a text box where users can add cars to a list. Each car is entered on a new line, and when the user presses enter, jQuery adds a \n to move to the next line. However, when I collect this string, the \n characters are "hidden" and cannot b ...

jquery ajax function that returns an object when successful

Below is a brief example of an AJAX call wrapped in a function. MyNS.GetStrings = function (successCallback, errorCallback) { var url = serverUrl + "/GetStrings"; $.ajax({ type: "GET", contentType: "application/json; charset=utf-8", dataType: ...

Issues with JSON data retrieved via Ajax requests

Recently, I created a page on WordPress with the intention of submitting a form via AJAX. However, every time the form is submitted, the URL changes to the form handler's URL and instead of using the JSON data to update the current page, it simply dis ...

What are some effective methods for resetting a state in @ngrx/store?

Lately, I've been grappling with a problem that's been on my mind for the past few days. Our team is developing an Angular 2 application, and my task involves creating a wizard for users to complete a form. I've successfully set up the dat ...

Displaying JSON data by aggregating the complete returned data

My code is shown below: public ActionResult PrintBarcodeLabel1(string data) { zplstr = zplstr + Environment.NewLine + zpl; return Json(zplstr, JsonRequestBehavior.AllowGet); } The expected return values are as follows: ^XA . . . li ...

Connecting a specific URL of an API to a single mobile app: A step-by-step guide

Currently, my API includes a user registration system that is utilized by a mobile application. Most of the URLs are restricted for anonymous users and require a token key for authorization, except for the register URL. The register URL needs to remain op ...

"I am trying to figure out how to set a link to an image using JavaScript. Can someone help me

I need help figuring out how to insert an image or gif file within two inverted commas '' in this line of code: _("status").innerHTML = ''; (line number 13 in the actual code) Your assistance with this question would be greatly appreci ...

In a multidimensional array, locate the key corresponding to the specified value

I am facing an issue with my code that involves an array containing various fruits with product ID and price as keys for different values. While I am able to retrieve the correct price, I am struggling to get the name of the chosen product. For instance, ...

Why aren't the kittens loading in Next Js?

Following the guidance in the Next Js documentation, I created a next.config.js file to inform Next Js that I want to incorporate kittens into my app. The resource for the kittens can be found at: This is how the next.config.js file appears: module.expor ...

Unable to transform SVG files in Next.js Jest version 28

Currently, my setup involves Next.js version 12.0.7, Jest version 28.1.0, and the use of the next-react-svg library for importing SVG files into components. The configuration in my jest.config.js file looks like this: // jest.config.js const nextJest = re ...

Having difficulty manipulating the answers by alternating, clicking, or hovering

I'm currently working on a template that includes 3 questions and answers that I want to hide initially, and have them revealed only when the user interacts by toggling, hovering, or clicking. I have successfully hidden the answers, but I am struggli ...

Is it necessary for two sibling elements to be of the same type in order for their margins to collapse together?

I am currently working on enhancing the visual appearance of a Bootstrap 4 card and encountered an issue: https://i.stack.imgur.com/p8Qzhm.png The spacing between the About the gig heading and the top Date item appears to be uneven. I would like to make ...

HTML steps for smooth scrolling to the top and bottom of a list

My HTML contains a vertical list with top and bottom arrows positioned nearby. I am looking to implement a function where clicking on the top arrow will move the list up gradually, and clicking on the bottom arrow will move the list down step by step. Belo ...

Convert numerical values to currency format

Here is a number 5850 that I would like to format as currency. Format Example 1: 5850 => $58.50 Format Example 2: 9280 => $92.80 I am utilizing the function below: Number.prototype.formatMoney = function(decPlaces, thouSeparator, decSeparat ...

Modifying Jquery script to maintain the effect continuously instead of just on hover

Recently, I came across a pulsing effect online that only works on hover. However, I want it to be a continuous effect and I'm not sure how to modify it to remove the hover requirement. The callbacks in jQuery are a bit confusing for me but I'm s ...

Recreating a <select> element and verifying it once more using JS/HTML5

Before I delve into my issue, I would like to offer an apology for any errors in my English. So, the HTML code I am working with looks like this: <body> <div id="container"> <div id="taskList"> <div id="firstTask"> & ...

Enhance User Experience by Implementing Event Listeners for Changing Link Visibility Using mouseover and getElementsBy

I am new to JavaScript and struggling to find a solution. Despite searching online for fixes, none of the solutions I've found seem to work for me. I have spent hours troubleshooting the issue but I must be missing something crucial. Can someone plea ...

Managing the hierarchy of controllers in CodeIgniter

I've been looking everywhere to find an example in Codeigniter on how to build a tree structure like the one below. If anyone can provide me with some assistance, it would be greatly appreciated. Specifically, when I click on child node 2, I want to ...

The hidden textbox loses its value when submitting

I have a form with fields and a RequiredFieldValidator. Additionally, I have another textbox that is hidden which gets populated by a JavaScript function: <script type="text/javascript"> $(document).ready(function (sender, args) { $("#myTextFiel ...