When utilizing the JavaScript createElement() method to create elements on keydown, it will not be compatible with jQuery's draggable() method

I'm currently developing a drag and drop feature for a project, allowing users to add items to a work area and then position them by dragging. I'm facing an issue where I want to create multiple instances of the same element using a key code, but the draggable functionality isn't working on elements created dynamically through a function. Is there a way to make sure that the draggable method works on dynamically created elements?

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Draggable Div Test</title>
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <style>
    .test {
      width: 50px;
      height: 50px;
    }
  </style>
  
  </head>
<body>
  <div id="area" style="border: 1px solid black; width: 500px; height: 500px;"> </div>
  
  <script>
    var area = document.getElementById("area");
    function duplicate(e) {
      switch(e.keyCode) {
        case 49:
        var test = document.createElement("div");
        test.classList.add("test");
        test.classList.add("draggable");
        console.log(test.classList)
        test.style.backgroundColor = "blue";
        area.appendChild(test);

        break
      }
    }
    document.addEventListener("keydown", duplicate)

    $( function() {
      $( ".test" ).draggable();
    } );
  </script>

</body>
</html>

Thanks

Answer №1

When using jQuery draggable, you can take advantage of the clone function:

 $(function() {
     i = 0

     $("#draggable").draggable({
         helper: 'clone',
         appendTo: "#droppable",
     });

    $("#droppable").droppable({
        accept: "#draggable",
    }); 

    i++;

    var $obj = ui.helper.clone().attr( 'data-name', 'newelementdropped' +i).draggable({
   stop : function (event, ui) {
    YOUR CODE
    });
}

To learn more about this topic, check out this helpful answer: Jquery draggable(), clone() to append div...Pls Fiddle my jsfiddle

Answer №2

Make sure to reinitialize the plugin once you've added the element.

For example, you can do this:

$(".element").sortable("destroy").draggable();

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

I need to fix the width of my background image in the URL - what's the best way to do

<div style="background-image:url('19.jpg');height:40px;position:fixed;width:1274px">hello </div> I'm trying to keep this div tag in a fixed position, but I also need to set a width for it. It seems like the background image is c ...

Refresh data with Axios using the PUT method

I have a query regarding the use of the HTTP PUT method with Axios. I am developing a task scheduling application using React, Express, and MySQL. My goal is to implement the functionality to update task data. Currently, my project displays a modal window ...

The built-in functions of Wordpress are not able to be identified in the ajax PHP file

As a newcomer to Wordpress development, I am facing challenges with implementing ajax on my WordPress site. I am currently working on a plugin that requires the use of ajax. However, my php file (xxxecommerce.ajax.php) is not recognizing the built-in Word ...

Ways to eliminate excessive spacing between grid blocks

Hey, I'm having an issue with displaying ads in a thumbnail format; there seems to be too much space between them. Take a look: I've been utilizing Bootstrap thumbnails to showcase products. echo '<div class="col-sm-6 co ...

What is the optimal way for text selection to operate within a clickable component on a web application?

We're currently developing a web application with expandable/collapsible elements. Here's an example of one of the clickable items: https://i.stack.imgur.com/jdLOu.png The text selection behavior when clicking on the element is causing some an ...

Is it possible to invoke JavaScript code from TypeScript?

I'm struggling with calling a JavaScript file from TypeScript. After resolving one import issue and adjusting the base function for tsc recognition, I'm now stuck on recognizing a declared function prototype in the JavaScript file. Although I ha ...

Transform a string into a property of a JSON object

One of my challenges involves extracting a value from a JSON object called Task, which contains various properties. Along with this, I have a string assigned to var customId = Custom_x005f_f3e0e66125c74ee785e8ec6965446416". My goal is to retrieve the value ...

Tips for including arguments in pm2 file execution

What steps should I take to run the cluster.js file on pm2 successfully? When I try executing the file locally with 'node cluster.js 0 1' command, it appends two arguments but encountering an error when using 'pm2 start "cluster.js 0 1"&apos ...

"An error occurred while trying to access the data for a new user on the snapshot object while navigating to the screen. It seems that the object is

When I navigate to the screen, I use componentDidMount to trigger fetchNewUser which is meant to detect a new user and update it if necessary. However, I encounter an issue where on initial navigation to the screen, it returns undefined is not an object ...

Using the .map function on JSON data with and without a parent element in JavaScript

In my current project, I am working on a React + Rails application. For handling JSON data, I typically use the default jbuilder in Rails. However, following the recommendations from the react-rails official documentation, I started adding a root node to m ...

modify the URL records within the GetJson function

My current address is "http://localhost:8000/index", and when I execute the following jQuery code: $.getJSON("1",function(data) { .....code }); It redirects to "http://localhost:8000/index/1". This works fine for now. ...

Include the data-title attribute within the <td> elements of my datatables

To apply the magic of jQuery datatables to all my tables, I use datatables. For responsive tables, I add data-title to my td's. Is there a way to automatically add data-title to all my td's like below? <td data-title="Fruit">Apple</td&g ...

Ways to inspect a number within a span and adjust its color depending on the value?

Can someone help me figure out why this code is not reading the value correctly? Check it out here This is the HTML: <a class="InterestLink">Click me</a> <div id="InterestExpander"> <div id="InterestExpanderX"> ...

Update Button Colour upon clicking the Button

I have multiple buttons lined up in a row on my webpage. I want the button's color to change when I click on them. Below is a snippet of my code: $( "button.change" ).click(function() { $(this).toggleClass( "selected" ); }); .Button { font-fa ...

transforming JSON information into tables on a webpage

Can someone help me with the challenge of incorporating a massive JSON file into an HTML table? I am encountering an issue where I continuously receive the error message Uncaught TypeError: v.forEach is not a function. Any guidance would be greatly appreci ...

Step by step guide to showcasing images dynamically in user interface

My current project involves displaying a screen with an HTML table and an image. The HTML table is fully dynamic. The Code Working Process When the user loads a page (with a URL), I render an HTML table in different parts as the page loads. I retrieve al ...

Saving a variable's value using Knockout loop within an HTML document

As a newcomer to KO, I have been utilizing the following code in my HTML file to print a specific value: <!-- ko foreach: { data: JSON.parse($parent.options), as: 'option' } --> <!-- ko if: option.label === 'AAA' || option. ...

Is Node.js or Express.js a server-side language like PHP or something completely different?

Hello, I have a question about Node.js and Express.js. I come from a PHP background and understand that PHP operations and functions execute on the server and return results to the client's screen. In simple terms, does Node.js/Express.js serve the s ...

Obtain the Text Content from a Knockout Dropdown Menu

Currently, I am facing an issue with extracting the text value of a selected option from a dropdown menu on my webpage. The dropdown contains various image categories and is defined as follows: <select class="form-control" data-bind="options: imageCate ...

The term "Highcharts does not exist"

I'm encountering an issue with my code: <html> <head> <title><%=sAtaskaitaTitle%></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name=vs_targetSchem ...