How to make an HTML element draggable without the need for an ID

I am currently working on making dynamically created divs draggable. While I have successfully achieved this with pre-existing div elements as shown below:

 <div>
  This can be dragged around, but outputs cannot?!
</div>

the issue arises when I try to make newly created divs draggable using the addElement() function.

To provide more context, my goal is to allow users to input text, which will then be displayed on the screen and able to be dragged around.

Here is the full code snippet:

function addElement () { 
  var text = document.getElementById("input").value;
  
  // creating a new div element 
  var newDiv = document.createElement("div");  

  // adding content to the new div
  var newContent = document.createTextNode(text); 
  
  // appending the text node to the newly created div
  newDiv.appendChild(newContent);  

  // inserting the new element and its content into the DOM 
  var currentDiv = document.getElementById("div1"); 
  document.body.insertBefore(newDiv, currentDiv); 

    document.getElementById("input").value = " ";

}

   $( function() {
  var div = document.getElementsByTagName('div');
    $( div ).draggable();
  } );
 div { width: 150px; height: 150px; padding: 0.5em; }
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>repl.it</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
      <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <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>
  </head>
  <body>
    <input id="input"type="text" placeholder=" text">
    <button onclick="addElement()" >Input</button>   
  
    <p>Outputs:</p>
     <script src="script.js"></script>
  </body>

</html>
 
<div>
  This can be dragged around, but outputs cannot?!
</div>
 
 
</body>
</html>

Answer №1

Upon page load, the draggable feature is attached to the existing div element. However, if you dynamically create a new div element, the draggable feature is not automatically applied to it. Therefore, whenever a new div is added, you must manually re-attach the draggable event to it:

function addElement() {
  var text = document.getElementById("input").value;
  // create a new div element 
  var newDiv = document.createElement("div");

  // and give it some content 
  var newContent = document.createTextNode(text);

  // add the text node to the newly created div
  newDiv.appendChild(newContent);

  // add the newly created element and its content into the DOM 
  var currentDiv = document.getElementById("div1");
  document.body.insertBefore(newDiv, currentDiv);

  $(function() {
    var div = document.getElementsByTagName('div');
    $(div).draggable();
  });

  document.getElementById("input").value = " ";

}

$(function() {
  var div = document.getElementsByTagName('div');
  $(div).draggable();
});
div {
  width: 150px;
  height: 150px;
  padding: 0.5em;
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>repl.it</title>
  <link href="style.css" rel="stylesheet" type="text/css" />
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <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>
</head>

<body>
  <input id="input" type="text" placeholder=" text">
  <button onclick="addElement()">Input</button>

  <p>Outputs:</p>
  <script src="script.js"></script>
</body>

</html>

<div>
  This can be moved around by dragging, why can't outputs?!
</div>


</body>

</html>

Answer №2

Upon loading the webpage, the draggable feature becomes associated with the pre-existing div element. However, if you generate a new element dynamically, the draggable functionality is not automatically applied to it. Each time a new div is added, it is necessary to manually re-attach the draggable event to ensure it works properly.

Answer №3

Running is all you do

$( function() {
  let element = document.getElementsByTagName('element');
  $( element ).draggable();
} );

Only on the initial load does it run, meaning any newly created elements are not draggable.

If you want these new elements to be draggable, simply add $( newElement ).draggable() to your addElement() function.

Answer №4

If you are utilizing $(callback), keep in mind that it only triggers the function once upon DOM load.
As a result, any new elements added afterwards will not automatically have drag functionality applied to them because the function responsible for it has already been executed.

To ensure that the newly added elements can also be dragged, you will need to explicitly call jQuery.draggable() on each of them after they are created.
This implies including newDiv.draggable() within the function that generates these elements.

Please Note

When working with an API such as jQuery, it is advisable to stick to its methods rather than relying heavily on native approaches. This consistency fosters better understanding and reduces cognitive switching between different coding paradigms.

Addendum

  • Your HTML contains errors due to having a <div> placed after closing both <body> and <html> tags, followed by unnecessary attempts to close them again at the end. While most browsers correct this mistake automatically, it's best practice to format your HTML accurately from the start.
  • Using $(document.createElement('div')) for creating jQuery-elements instead of $('<div>') offers slight performance benefits. It is recommended to follow this method.
  • Avoid adding the onclick listener directly in the HTML markup. Instead, attach event listeners dynamically through JavaScript to prevent global namespace pollution. This approach maintains code encapsulation and cleanliness.

Incorporating more jQuery in your code could resemble the following:

$(function() { // Executed once DOM loaded
  // Make all existing 'div' elements draggable
  $('div').draggable();
  
  // Attach click event using jQuery
  $('button').click(function() {
    // Create a new jQuery element using efficient syntax discussed in sub-notes
    var newDiv = $(document.createElement("div"));
    newDiv.text($('#input').val()); // Set text value from 'input'
    newDiv.draggable(); // Enable dragging

    $('body').append(newDiv); // Add to body

    $('#input').val(''); // Clear 'input' field
  });
});
div {
  width: 150px;
  height: 150px;
  padding: 0.5em;
}
<!DOCTYPE html>
<html>
  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  </head>
  <body>
    <input id="input" type="text" placeholder="text">
    <button>Input</button>

    <p>Outputs:</p>
    <div>
      This can be dragged around, but outputs cannot?!
    </div>
  </body>
</html>

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

Rotating an input 90 degrees within a div for unique positioning

I used JavaScript to make an input range vertical, like so: var range_pitch = document.createElement("input"); range_pitch.setAttribute("type", "range"); range_pitch.style.webkitTransform = "rotate(90deg)"; range_pitch.style.mozTransform = "rotate(90deg)" ...

I am looking to optimize my WordPress posts to load in increments as the user scrolls down the page, similar to how Facebook does

I am looking to implement a feature on my WordPress post where the content loads a few at a time as the user scrolls, similar to Facebook. Specifically, I would like my webpage to automatically load 10 posts and then continue loading 10 more as the user re ...

Is there a way for me to choose every element excluding those contained within a specific div?

Check out my code snippet: <div class="car"> <div class="make">NISSAN</div> <div class="model">MICRA</div> </div> <div class="discontinued"> <div class="car"> <div class="make">FOR ...

Aligning dynamically-sized TextInput in React Native

I am facing a challenge in centering a text input with a width that matches the length of the input text. I have tried using alignSelf: 'center' and alignItems: 'center', but the text input is not visible without specifying a width. Fo ...

Error: Oops! The super expression can't be anything other than null or a function in JavaScript/TypeScript

I am facing an issue with class inheritance in my code. I have a class A that extends class B, which in turn extends class C. Whenever I try to create a new instance of class A within a function, I encounter the following error message: Uncaught TypeError: ...

Only one instance of the Next.js inline script is loaded

Incorporating Tiny Slider into my Next.js application has been a success, but I am facing an issue with the inline script that controls the slider's behavior. The script loads correctly when I first launch index.js. However, if I navigate to another p ...

There is nothing like Python Bottle when it comes to parsing JSON data from

In my React code, I have the following: const payload = { x : x, y : y } fetch("http://localhost:8080/update_game", { method: "POST", body: JSON.stringify(payload)}) And in Python, I have this implementation: @post(&ap ...

Using a for loop to cycle through an array and generate sibling div elements

I'm attempting to display the content of the gameTwo array in two child divs under the game2 element. However, the issue I'm facing is that the loop creates a child of a child on the second iteration. Could someone provide guidance on how I can a ...

What is preventing me from merging these two arrays together?

Here is some code for a Vuex mutation: export const CREATE_PANORAMAS = (state, panoramas) => { console.log('building.panoramas:', state.building.panoramas) console.log('panoramas:', panoramas) state.building.panoramas.concat(p ...

The absence of a defined HTMLCollection [] is causing an issue

rowGetter = i => { const row = this.state.estimateItemList[i]; const selectRevison = this.state.selectedEstimate.revision; const rowLenght = this.state.estimateItemList.length; const changeColor = document.getElementsByClassName('rd ...

Center the p tag vertically

To ensure the text inside the p tag aligns vertically in the middle, I've set a specific height for the tag. While this works perfectly for single-line text, it shifts to the top of the p tag when there are two lines of text. It's important to k ...

Dynamically insert a new row into an HTML table using AJAX and refresh the table with .load method

I am facing an issue with my HTML table that loads data dynamically through a PHP snippet containing SQL queries. There is a Select option and a button on the table to add a new row, which triggers an AJAX procedure to send the data to PHP for insertion in ...

Executing background operations in Meteor.js

Let me lay out my situation: 1. Extracting data from example.com at regular intervals 2. Storing it in a Mongodb database 3. Subscribing to this data in a Meteor App. Since I'm still learning Meteor, here's my plan: 1. Develop a scraper script ...

Effects with Cleanup - terminates ongoing API calls during cleanup process

Developing a React album viewing application: The goal is to create a React app that allows users to view albums. The interface should display a list of users on the left side and, upon selecting a user, show a list of albums owned by that user on the righ ...

AngularJS text markers

In order to streamline the process of managing tags with random content, I have devised a 'tag' manipulation system using the angular-ui alert mechanism. The system includes a factory and a directive as follows: Factory: app.factory( &a ...

Discover results while inputting in the search box

Can anyone assist me? I'm looking to enhance my current code by adding a search functionality to the ul list. I want users to be able to type in a search term and have the matches automatically highlighted as they type, similar to a "find-as-you-type ...

Tracking the number of form submissions on a PHP website

I am looking to add a counter feature to my website where every time a form is submitted, the count increases for all visitors. The starting number will be 0 and each form submission will increment the count. While I can manage the count using JS/jQuery w ...

Utilizing the closest method to set selection choices within a table's select tag

Currently, I am attempting to populate dynamic options in a select tag that is located within a table. The number of rows in this table can vary based on certain conditions. After retrieving the data via ajax, I am running into issues when trying to set i ...

Symfony2 compresses CSS and JS files to improve performance

Currently, I am attempting to execute php app/console assetic:dump in order to test my production environment. While my css file gets generated successfully, the js file does not. The following error message is displayed : C:\wamp\www\p ...

Incorporate a dynamic fading effect for text and images using JQuery

I successfully implemented a Crossfade effect using Jquery: function doAnimationLoop(o, n, t, i, a) { fadeInOut(o, n, t, i, function() { setTimeout(function() { doAnimationLoop(o, n, t, i, a) }, a) ...