Is the drag-and-drop feature not working properly?

I'm new to coding in Javascript and I'm attempting to insert an image inside a border created with CSS. Unfortunately, the script doesn't seem to be working properly. It's possible that there is a small error in the code causing the issue.

Although the snippet functions correctly, the image does not display as expected.

"e" stands for event. In my code, I have functions for drag(e), allowdrop(e), and drop(e).
Thanks

<!doctype html>
<html>

<head>
  <title>drag and drop</title>

  <style type="text/css">
    #targetDiv {
      margin-left: 300px;
      width: 200px;
      height: 150px;
      padding: 10px;
      border: 1px solid #999999;
    }
  </style>

</head>

<body>
  <h1>drag and drop</h1>

  <div id="targetDiv" ondragover="allowDrop(event)" ondrop="drop(event)"></div>
  <img id="dragItem" src="market-street-car.jpg" width="200" height="150" draggable="true" ondragstart="drag(event)" />

  <script>
    function drag(e) {
      e.dataTransfer.setData("Text", e.target.id);
    }

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

    function drop(e) {
      var dragItem = e.dataTransfer.getData("Text");
      e.preventDefault();
      e.target.appendChild(document.getElementById(dragItem));
    }
//You don't need to edit this one cuz you don't need var var is probably optional

  </script>

</body>

</html>

Answer №1

Here is the revised version. You seem to have omitted a ")" character, but I've rectified it by adding a "var" expression right here: take.ms/el76e

<!doctype html>
<html>

<head>
  <title>drag and drop</title>

  <style type="text/css">
    #targetDiv {
      margin-left: 300px;
      width: 200px;
      height: 150px;
      padding: 10px;
      border: 1px solid #999999;
    }
  </style>

</head>

<body>
  <h1>drag and drop</h1>

  <div id="targetDiv" ondragover="allowDrop(event)" ondrop="drop(event)"></div>
  <img id="dragItem" src="market-street-car.jpg" width="200" height="150" draggable="true" ondragstart="drag(event)" />

  <script>
    function drag(e) {
      e.dataTransfer.setData("Text", e.target.id);
    }

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

    function drop(e) {
      e.preventDefault();
      var dragItem = e.dataTransfer.getData("Text");
      e.target.appendChild(document.getElementById(dragItem));
    }
  </script>

</body>

</html>

Answer №2

It seems that there is an issue with the code not interacting correctly with the image. When testing the code snippet, only the output of the "allowDrop" function is visible. A possible reason for this could be an error within your dragItem element:

ragstart="drag(event"   

The above code is missing a closing parentheses ")"

When troubleshooting Javascript, I always recommend opening the Js console (ctrl+shift+j) to closely monitor any errors that may occur while navigating through the page. Sometimes, errors might briefly appear in the console that are not immediately visible when only running the page itself.

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 method does Apple use to apply overflow:hidden to elements within position:fixed?

After conducting my own experiments and delving into the topic online, I discovered that elements using position: fixed do not adhere to the overflow: hidden property of their parent element. This also applies to children within the fixed positioned elemen ...

Enhance the usability of input-group-addon elements in Bootstrap by incorporating focus and validation states, rather than focusing

When using Bootstrap, focusing on an input activates a blue border and box shadow to show where the user's attention is. If there are validation states such as error, warning, or success, a red, yellow, or green border will be added accordingly. An ...

Why Does Angular's ngIf Always Result in a Negation to True?

Can someone please clarify this for me? I'm having trouble understanding why the *ngIf condition and else statement always evaluate to true unless I am completely mistaken. Here is the situation: I have an icon that should turn the background color t ...

Issue with CSS not appearing in Google Chrome's coverage tab

As I delve into analyzing the extent of unused CSS on my webpage, I encounter a challenge. The webpage is crafted in Angular 7, with CSS incorporated through the angular.json build configuration. The css appears to be added to the head of the html file, e ...

Implementing a strategy to prevent the browser's back button from functioning

Is there a way to prevent the user from using the back button in a single page application? I've tried methods like onhashchange and window.history.forward, but they don't seem to be effective (perhaps because the URL doesn't change). ...

Connect main data to sub-component

Example Vue Structure: <Root> <App> <component> Main function in main.js: function() { axios.get('/app-api/call').then(function (resp, error) { _this.response = resp.data; }) ...

Failure to validate two dates, even when they are both in date format within AngularJS

Although it may seem silly to ask, I am confused as to why this is not working. Even though all the values appear fine in debug mode. My goal is to display an error if the productionStartFrom date is before the current date. Controller scope.currentDate ...

Technique for updating URL when submitting a form on a webpage

I'm a newcomer to the world of coding and I have a simple issue that needs fixing. I want to create a form field where users can input the last segment of a URL provided to them. After entering this segment, I want the page to refresh automatically a ...

Managing the height of a TextArea within a Flexbox environment

After exploring various methods for achieving auto-height in a textarea, I decided to go with the contenteditable approach as it seemed cleaner to me. However, while it worked perfectly on its own, it failed when placed within flexbox containers. I experi ...

Modifying the appearance of Bootstrap 4 Nav-tabs using CSS

I have implemented Bootstrap 4 Nav-tabs as shown below: <ul class="nav nav-tabs" id="myTab" role="tablist"> <li class="nav-item"> <a class="nav-link active" id="home-tab" data-toggle="tab" href="#home" role="tab" aria-controls="home" ...

Struggling to integrate the c3 chart library with Angular, encountering loading issues

I've been attempting to utilize the c3 angular charts, but unfortunately nothing is displaying on my page. Despite checking for console errors and following a tutorial, I still can't seem to get anything to show up. I have cloned the git repo an ...

Using PHP to read an image blob file from an SVG

Currently, I am utilizing the Raphael JS library on the client-side to generate a chart in SVG format. However, my goal is to make this chart downloadable, which poses a challenge since SVG does not natively support this feature. Initially, I attempted to ...

Tips for utilizing the "g" element in SVG within CoffeeScript to rotate an object in D3

I'm experimenting with creating a design similar to the following SVG code snippet: <svg width="12cm" height="4cm" viewBox="0 0 1200 400" xmlns="http://www.w3.org/2000/svg" version="1.1"> <desc>Example rect02 - rounded rectangles&l ...

Prolong the ultimate position of the initial animation for the translated object

I understand that this question has been asked multiple times before, but I am seeking a fresh approach to these animations. Issue: The second box contains multiple animations, and I am trying to achieve the same effect as the first one. However, it seem ...

Which specific combination of jQuery selectors is most effective for modifying the text contained within span tags?

Here is some HTML code that I need help with: <tr> <td> <img id='1' class='promote' src='/images/plus.png' /> <span>0</span> <img id='1' class='demote' src=&a ...

Adjusting transparency on various DIV elements

Currently, I am working on implementing the 'OnClick' functionality in jQuery. The goal is to have only the parent div and its child divs displayed when we click on the parent div property, while fading out all other divs. Below you can find the ...

Working with Three.js: Retrieving an object post-loading using GLTF Loader

Is there a method in three.js using the GLTF loader to access an object for transformations after it has been loaded? It seems like attempting this approach does not yield results gltf.scene.position.set(10,10,10) Sample Code: function getObject(){ ...

"Troubleshooting issues with Material Design components in AngularJS: Why is <md-select> not functioning correctly

I'm attempting to implement the <md-select> tag, but I can't seem to achieve the same result as shown here. This is the code I've written: <div layout="column" layout-align="center center" style="margin: 0px 10px 0px 5px;"> & ...

Identifying and locating white-colored text within an HTML document

My HTML file has the following structure: <HTML> <HEAD> <style> .secret { background-color: black; color: black; } </style> </HEAD> <BODY ...

Looking to retrieve the dynamic "Publish Date" value from a webpage using HtmlUnit in Java?

As part of a coding exercise, I am currently working on a project that involves comparing the current system date with dates on various web pages to determine if there are any new updates. While most of the pages work as expected, there is one particular p ...