Learn how to utilize Javascript to easily drag and drop an image within the same block

I am encountering an issue with dragging and dropping images or swapping them using JavaScript. I have tried to implement this in the code below, where clicking on icons moves them onto a colored div. However, I am now trying to drag and drop the images within the div or even swap them around. I am struggling to achieve this. Can someone please assist me with this task?

Thank you in advance.

This is the code I have:

function changeHome() {
  document.getElementById('color').style.backgroundColor = "coral";
}

function changeGray() {
  document.getElementById('color').style.backgroundColor = "gray";
}

function changeRed() {
  document.getElementById('color').style.backgroundColor = "red";
}

function changeGreen() {
  document.getElementById('color').style.backgroundColor = "green";
}

function changeBlue() {
  document.getElementById('color').style.backgroundColor = "blue";
}

$(document).ready(function() {
  $('.image').click(function() {
    var srcimg = $(this).attr('src');
    $('#color').append("<img src=" + srcimg + "  width='70' height='70'>");
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<br/>
<div class="container">
  <h1 align="center"><u> JavaScript Simple learning </u></h1>
  <h3 align="center"> Use of JavaScript to drag and drop icons in Background image </h3>
  <br/> <br/>
  <div class="col-md-10">
    <div id="color">
    </div>
  </div>
  <div class="col-md-2">
    <button onclick="changeHome()"> Home Color  </button> <br/><br/><br/>
    <button onclick="changeGray()"> Click for Gray </button> <br/><br/>
    <button onclick="changeRed()"> Click for Red </button> <br/><br/>
    <button onclick="changeGreen()"> Click for Green </button> <br/><br/>
    <button onclick="changeBlue()"> Click for Blue </button> <br/><br/>
  </div>
</div>
<div class="container">
  <h2><u> List of Icons </u></h2>
  <img class="image" src="images/fb.jpeg" width="70" height="70" />
  <img class="image" src="images/twitter.jpeg" width="70" height="70" />
  <img class="image" src="images/linkedin.jpeg" width="70" height="70" />
  <img class="image" src="images/gmail.jpeg" width="70" height="70" />
  <img class="image" src="images/instagram.jpeg" width="70" height="70" />
  <img class="image" src="images/whatsapp.jpeg" width="70" height="70" />
  <img class="image" src="images/telegram.jpeg" width="70" height="70" />
</div>

Answer №1

If you need to implement drag and drop functionality in JavaScript, there are two distinct methods you can use. One involves appending an image, while the other is for replacing an image. Below is an example of how you can achieve this:

SCRIPT Content

<script>
        function changeHome() {
            document.getElementById('color').style.backgroundColor = "coral";
        }

        function changeGray() {
            document.getElementById('color').style.backgroundColor = "gray";
        }

        function changeRed() {
            document.getElementById('color').style.backgroundColor = "red";
        }

        function changeGreen() {
            document.getElementById('color').style.backgroundColor = "green";
        }

        function changeBlue() {
            document.getElementById('color').style.backgroundColor = "blue";
        }
        $(document).ready(function () {
            $('.image').click(function () {
                var srcimg = $(this).attr('src');
                var imgid = $(this).attr('id');
                console.log($(this));
                $('#color').append('<div ondrop="drop(event)"  ondragover="allowDrop(event)" style="float:left;display:block;height:50px;width:50px"><img id=' + imgid + "1" + ' src=' + srcimg + ' draggable="true" ondragstart="drag(event)" width="70" height="70">');
            });
        });

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

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

        function drop(ev,ui) {
            console.log("evvv" + ev.srcElement);
            console.log($(this).parent('div'));
            ev.preventDefault();
            var src = document.getElementById(ev.dataTransfer.getData("src"));
            var srcParent = src.parentNode;
            if (srcParent.parentNode.id == "div1")
            {
                var data = ev.dataTransfer.getData("src");
                ev.target.appendChild(document.getElementById(data));
            }
            else
            {
                var tgt = ev.currentTarget.firstElementChild;

                ev.currentTarget.replaceChild(src, tgt);
                srcParent.appendChild(tgt);
            }

        }
        function drop1(ev) {
            ev.preventDefault();
            var data = ev.dataTransfer.getData("src");
            ev.target.appendChild(document.getElementById(data));
        }
    </script>

HTML Content

    <div class="container">
        <h1 align="center"><u> JavaScript Simple learning </u></h1>
        <h3 align="center"> Use of JavaScript to drag and drop icons in Background image </h3>
        <br /> <br />
        <div class="col-md-10">
            <div id="color" style="height:100px" ondragover="allowDrop(event)" ondrop="drop(event)" >
            </div>
        </div><br /><br />
        <div class="col-md-2">
            <button onclick="changeHome()"> Home Color  </button> <br /><br /><br />
            <button onclick="changeGray()"> Click for Gray </button> <br /><br />
            <button onclick="changeRed()"> Click for Red </button> <br /><br />
            <button onclick="changeGreen()"> Click for Green </button> <br /><br />
            <button onclick="changeBlue()"> Click for Blue </button> <br /><br />
        </div>

</div>
<div class="container" id="div1">
    <h2><u> List of Icons </u></h2>
    <div style="float:left;display:block">
        <img class="image" id="img1" src="Images/natural.jpg" width="70" height="70" draggable="true" ondragstart="drag(event)" />
    </div>
    <div style="float:left;display:block">
        <img class="image" id="img2" src="Images/nature2.jpg" width="70" height="70" draggable="true" ondragstart="drag(event)" />
        </div>
    <div style="float:left;display:block">
        <img class="image" id="img3" src="Images/sunset.jpg" width="70" height="70" draggable="true" ondragstart="drag(event)" />
        </div>
    <div style="float:left;display:block">
        <img class="image" id="img4" src="Images/dp1.jpg" width="70" height="70" draggable="true" ondragstart="drag(event)" />
        </div>
    <div style="float:left;display:block">
        <img class="image" id="img5" src="Images/dp2.jpg" width="70" height="70" draggable="true" ondragstart="drag(event)" />
        </div>
    <div style="float:left;display:block">
        <img class="image" id="img6" src="Images/guitar.jpg" width="70" height="70" draggable="true" ondragstart="drag(event)" />
        </div>
    <div style="float:left;display:block">
        <img class="image" id="img7" src="Images/images.jpg" width="70" height="70" draggable="true" ondragstart="drag(event)" />
        </div>
    </div>

Answer №2

To delete a single photo with a double click event, you can utilize the following function:

JavaScript Function

function DeleteImage(element)
        {

            element.parentElement.remove();  //removes the parent div of the image
            element.remove();  //removes the image itself
        }

HTML Code

  <img ondblclick="DeleteImage(this)" width="70" height="70">

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

Arrange 4 divs (children) at each corner of the parent element

Currently, I am facing a challenge in positioning 4 divs in the corners of their parent div. The HTML code structure is as follows: <div class="resize"> <div class="n w res"></div> <div class="n e res"></div> < ...

Accessing and fetching data from a PostgreSQL database using JavaScript through an API

I am currently working with an npm package called tcmb-doviz-kuru to fetch currency data from an API and then insert it into my database. However, I am facing an issue with mapping the data to properly insert the values. Below is my code snippet: var tcmbD ...

"Web fonts without a content delivery network (CDN)

When it comes to loading fonts via CDN, I am facing an issue with the requirements for a specific font. We are currently using Montserrat Light in some sections, but unfortunately, my preference according to Google Fonts does not include the 'light&ap ...

Interacting with a card in vuejs won't trigger any action

Is there a way to make an overlay disappear when clicking anywhere on the screen except for a specific card positioned on top of it? The current setup makes the overlay disappear even when the card is clicked. How can this behavior be corrected? <div ...

Unable to activate focus() on a specific text field

It's quite peculiar. I'm working with a Sammy.js application, and my goal is to set the focus on a text field as soon as the HTML loads. Here's the CoffeeScript code snippet I've written: this.partial('templates/my-template.jqt&ap ...

Creating a versatile TailwindCSS grid that can adjust to varying numbers of grid columns

I am currently working with Vue3 and TailwindCSS, attempting to create a grid using a dynamic grid-cols-{n} class. While I am aware that TailwindCSS typically supports up to 12 columns by default, the challenge arises when the number of columns needed is e ...

Convenient method for extracting the final element within a jQuery section

I need to determine whether the div with the class "divclass" contains an anchor tag. If it does, I have to run a specific block of JavaScript code; otherwise, no action is required. <div class="divclass"> <span> some text</span> ...

Scheduling tasks for jQuery/Javascript like a Cronjob

I'm currently working on a web application that predominantly uses PHP, however, I am incorporating jQuery/Javascript to retrieve Tweets from users' URLs at http://twitter.com/status/user_timeline/joebloggs.json?count=1&callback=. My aim is ...

Refreshing a page occurs every 30 seconds or upon the user submitting a form

My PHP page consists of various includes for different sections of a video website. One of these sections is a comments area where users can submit their feedback to a database successfully. However, I want to ensure that only the specific included page/di ...

Creating a stunning 2D image from a 3D scene through the power of raytracing with webgl and three.js

My goal is to project a 3D scene onto a 2D plane using ray tracing. Although my ultimate aim is volume rendering, I am currently struggling with the basics. I have set up a three.js scene with the viewing plane attached to the camera in front of it. The S ...

Comparing functions and function issues when using onClick in JavaScript

I have successfully created an Image Element on my web page dynamically using JavaScript. I am now trying to set an onClick event for the newly created image element. However, I am encountering a problem and I cannot figure out why?, This is the code I ...

Delayed callback on blur

I am developing an AutoComplete feature in React that displays a list of suggested completions as the user types into a text box. When a suggestion is clicked, it should trigger a callback function, and the dropdown should disappear when the text box loses ...

Storing data from one file into a different directory in PHP

As a php beginner, I have discovered that the most effective tool for working with MySQL databases and files is php. Currently, I am trying to retrieve a file with the name 'file_name'. <input type=file name="file_name"> and then save th ...

Utilize Bootstrap and Flat UI to enhance the design of a div, or duplicate the styles to apply to the navbar

My navigation bar was created using Bootstrap and Flat UI on top of it. However, when I try to incorporate bootstrap+flat ui into another HTML+CSS file that I have, the hexagons end up looking distorted. It seems like my navigation bar only works with flat ...

Conceal dynamically generated div elements created with ngIf

I am currently working on initializing this div using ngOnInit in Angular ngOnInit(): void { let optTemp = ''; for (let data of arrOption) { optTemp = optTemp + '<option>' + data.trim() + '</option> ...

Shorten a data point in JSON code

I'm currently in the process of developing a stock widget that utilizes JSON to retrieve data from the Yahoo API/YQL console. I am specifically working with values extracted from the key ChangePercentRealtime, however, the values are longer than what ...

Incorporating EJS Template Body Parameters into AWS Lambda's Handler.js Using Serverless.yml

I have a scenario where I am trying to embed an EJS template named 'ui.ejs' into my handler.js file. The goal is to extract URL query parameters, then pass them to a function called 'ui.js' to retrieve data, which will then be displayed ...

What is the best way to retrieve both the start and end date values from a React date range picker component

I have integrated a date range picker npm package called react-date-range into my code. On my screen, there is an "Apply Dates" button. When this button is clicked, I want to retrieve the selected date range value. How can I achieve this onclick event? ...

Is there a way to extract both a and b from the array?

I just started learning programming and I'm currently working on creating an API call to use in another function. However, I've hit a roadblock. I need to extract values for variables a and b separately from the response of this API call: import ...

Silly problem arising from the animate feature in jQuery

Apologies for my poor English. I am facing an issue with the animate function of jQuery in my code snippet. It seems to work fine at line 2, but it doesn't work at line 3. Can someone help me understand why? $('.opac').hover(function(){ ...