Dragging and dropping elements using Jquery to various positions on the screen

I am working on a project with draggable buttons and a droppable textarea. When I drag a button onto the textarea, it displays some code. If I drag another button, the text related to that button is added to the existing code.

My query is how can I insert the text from my next button between those two snippets of code?

This snippet shows the code I am using:

Script:

$("button").click(function () {
    $("#div1").empty();
});

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

function drag(ev) {
    ev.dataTransfer.setData('Text/html', ev.target.id);
}

function drop(ev, target) {
    ev.preventDefault();
    var data = ev.dataTransfer.getData("text/html");

var function1 = "test1{ \n\n\n}";
var function2 = "test2{ \n\n\n}";
var variable1 = "var first;";    
var variable2 = "var second;";

    console.log("****",target);

    if (data == "test1") {
        if (data) {
            $('#div1').append(function1);
        }
    }
    if (data == "test2") {
        if (data) {
            $('#div1').append(function2);
        }
    }
     if (data == "test3") {
        if (data) {
            $('#div1').append(variable1);
        }
    }
     if (data == "test4") {
        if (data) {
            $('#div1').append(variable2);
        }
    }
}

HTML:

<table>
    <tr>
        <td>
            <button id="test1" ondragstart="drag(event)" draggable="true">Function-1</button><hr>
            <button id="test2" ondragstart="drag(event)" draggable="true">Function-2</button><hr>
            <button id="test3" ondragstart="drag(event)" draggable="true">Variable-1</button><hr>
            <button id="test4" ondragstart="drag(event)" draggable="true">Variable-2</button><hr>
        </td>
        <td>
            <textarea id="div1" ondrop="drop(event, this)" ondragover="allowDrop(event)"></textarea>
        </td>
    </tr>
</table>
<br>
<button>Clear</button>

Fiddle: http://jsfiddle.net/ktL02h7u/16/

Answer №1

I included jQuery UI in your fiddle and converted the texarea to a <pre> tag. Additionally, I enclosed all the lines you input within a <code> tag so that they can be draggable elements.

Upon page load, I utilized $("#div1").sortable(); to make the children sortable. You have the option to add transitions to smoothly move the elements into place if desired.

Take a look at it here: http://jsfiddle.net/ktL02h7u/32/

function drop(ev, target) {
    ev.preventDefault();
    var data = ev.dataTransfer.getData("text/html");

var function1 = "test1{ \n\n\n}";
var function2 = "test2{ \n\n\n}";
var variable1 = "var first;";    
var variable2 = "var second;";


    if (data == "test1") {
        if (data) {
            $('#div1').append("<code>"+function1+"<br></code>");
        }
    }
    if (data == "test2") {
        if (data) {
            $('#div1').append("<code>"+function2+"<br></code>");
        }
    }
     if (data == "test3") {
        if (data) {
            $('#div1').append("<code>"+variable1+"<br></code>");
        }
    }
     if (data == "test4") {
        if (data) {
            $('#div1').append("<code>"+variable2+"<br></code>");
        }
    }
}
$(function() {
        $( "#div1" ).sortable();
  });

UPDATE: Significant code modification once I grasped that you intended to drop inside elements: http://jsfiddle.net/ktL02h7u/66/

function drop(ev, target) {
    debugger;
    ev.preventDefault();
    var data = ev.dataTransfer.getData("text/html");
    var $target = target ? $(target) : $(ev.target);
    var elementTypes = {
        test1: "test1{ \n\n\n<span class='functionClose'>}</span>",
        test2: "test2{ \n\n\n<span class='functionClose'>}</span>",
        test3: "var first;",
        test4: "var second;"
    }   

    if(data){
        var el = $("<code>"+elementTypes[data]+"<br></code>");
        if(el.find("span").length > 0){
            el.on("dragover",function(ev){
                console.log("dragged over");
                ev.preventDefault();  
                ev.stopPropagation();
                allowDrop(ev);
            }).on("drop", function(ev){
                console.log("dropped over");
                ev.preventDefault();  
                ev.stopPropagation();
                drop(ev.originalEvent,el.find("span")[el.find("span").length -1]);
            });
        }
        if($target.hasClass("functionClose")){
            $target.before(el);
        }
        else{
            $target.append(el);
        }                            
    }

}

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

Execute a database query to search for patterns using Regular Expressions within the

As I embark on a new project, I find myself questioning my approach before diving in too deep and realizing it may not be the most efficient path. Within the realm of a large company where we develop unofficial tools for internal use, I am faced with limi ...

Issues with displaying Base64 images in Fancybox2 on Internet Explorer

I want to incorporate a base64 image into fancybox. This is the code I am using: <script type='text/javascript' src='http://code.jquery.com/jquery-1.8.3.js'></script> <link rel="stylesheet" href="http://cdnjs.cloudflare ...

What significance does the slash hold in a package name when using require for an npm package?

When we "require" non-local NodeJS modules, what does the slash in the module name signify? For instance: from the GitHub page of the ShellJS npm module (link: https://github.com/shelljs/shelljs#javascript) require('shelljs/global'); requir ...

React JS's popup feature can be unreliable, as it tends to break the application frequently

I have been developing a web application that interacts with a public API and presents the retrieved data in a table format. However, I am encountering an issue where clicking the "Click to Display Hottest Planet" button sometimes results in an error. How ...

Transmitting a form containing an associative array through AJAX to PHP

Recently, I've been working on a form that has fields of an associative array: <label for="my_array[][system]">System</label> <input id="my_array[][system]" type="text" value="" name="my_array[0][system]"> <label for="my_array[] ...

Dividing the z-index by half of the shape

I am trying to achieve the following shape: https://i.stack.imgur.com/Lr9gv.png So far, I have attempted the following code. How can I combine these elements together? .clal-loader{ display:flex; } .clal-loader div{ border: 10px solid #38477e; b ...

What is the best way to create a reactive prop within this Vue 3 application?

I've been developing a news application using Vue 3 along with the News API. My current focus is on implementing a search feature. Within my App.vue file, I have: <template> <TopBar @search="doSearch" /> <div class=" ...

What is the reason that prototypes are not passed down through inheritance?

Can anyone shed light on why Validator.js is structured the way it is initialized (as shown in the first code snippet) and the reason behind the inability to call the validate method (as demonstrated in the second snippet)? I am currently experimenting wi ...

The Benefits of Semantic Class Names compared to Microdata

As I strive to use semantic class names, my exploration of microdata and SEO raises a question: Is it necessary to use both? Compare these two HTML snippets representing an event: Using CSS classes: <div class="event" itemscope itemtype="http://schema ...

What is the best method to enable horizontal scrolling within a div element by overflowing its content?

My layout looks like this: <div id='container'> <div id='cont1' style='width:150px'>Content 1</div> <div id='cont2' style='width:150px'>Content 2</div> <div id=' ...

Django is refusing to display my CSS and JavaScript files - static files

Within my code in settings.py, I define the static URL like so: STATIC_ROOT = os.path.join(BASE_DIR, "static") STATIC_URL = '/static/' The location of my static files and folders is at /home/myLinuxUsername/myApp/static/interactive-preview-depe ...

What is the optimal placement for promises in Angular: Factory or Controller?

In my application, I have a basic factory to manage API calls. Currently, the structure looks like this: .factory('apiFactory', function($http){ var url = 'http://192.168.22.8:8001/api/v1/'; return { getReports: function() { ...

Close the overlay by clicking outside of it

I'm working on creating a unique pop-up window that appears when a customer adds a product to their cart. The design features red and green background divs with a darker overlay (#overlay-daddy) and a white child div (#overlay). My issue arises from ...

What is the method for sending arguments to material avatar using require?

import Avatar from '@material-ui/core/Avatar'; Here is an example of working code: <Avatar alt="user 4" src={require('Assets/img/user-1.jpg')} className="size-80 rounded-circle border-info rct-notify" /> However, I encountered ...

Is it possible to test an Angular application using Protractor within an iframe that is hosted by a non-Angular

While trying to migrate a legacy app to Angular, we encountered an issue where the legacy app loads the new app in an iframe. Testing this integration with Protractor has proven challenging due to the fact that the legacy app is not built on Angular. If t ...

Tips for aligning the box beside another

How can I arrange 2 boxes in one line and the other 2 in the next line? Currently, they are all showing up on separate lines. Can anyone provide a solution to this issue? body{ background:#f4f4f4; color:#555; font-family:Bahnschrift SemiCond ...

Adjust the container width to match the width of the visible thumbnails?

Take a look at my website over at: . If you want to see more thumbnails, consider switching to a different album. The album titled Paris contains the most images. If you press the "Show Photo Grid" button located in the bottom-right corner, you'll be ...

Unexpected failure of Ajax response following a successful upload

I am currently using jQuery to upload files or images to a CodeIgniter controller. Despite facing some challenges, I have successfully managed to upload the image. However, I am encountering some strange behavior from the AJAX function. Issue: The AJAX ca ...

Ways to use jQuery to disable row form elements in the second and third columns

I need a way to deactivate form elements in the second and third columns, starting from the second row until the nth row using a jQuery selector. <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/> ...

Troubleshooting problem with printing iframes on Firefox

When attempting to print an iframe with a large amount of data using the code below, I'm encountering an issue in Firefox where only the first page is printed. The rest of the pages are not being included in the printout. window.frames[frameID]. ...