Use JavaScript to smoothly move a span to a specific location on the page

My challenge lies in enabling users to dynamically create a span at any desired location upon clicking the "Link" button. The issue I'm facing is that although I set the attribute draggable="true" for the dynamically created span, it remains fixed within the "smsArea" section due to the existing drag function.

Is there an easier way to implement drag & drop functionality for elements within a specific area?

Answer №1

After much exploration, I stumbled upon a solution using the following method: window.getSelection().getRangeAt(0);

var area = document.getElementById("template");
var message = document.getElementById("message");
var maxLength = 160;
var re = new RegExp("ô|â|ê|ç");

var myTags = new Object();

myTags['company']   = '#ENTREPRISE#';
myTags['city']      = '#VILLE#';
myTags['link']      = '#LIEN#';
myTags['firstname'] = '#PRENOM#';
myTags['lastname']  = '#NOM#';
myTags['title']     = '#TITRE#';

$(document).ready(function() {
    // first 2 divs (what's already rendered) will be made draggable
    $("#test").draggable();
    
    // listen for new divs added, make these new elements draggable
    $("#smsArea").on("DOMNodeInserted", "#test", makeDraggable);
    
    // next 3 divs inserted are draggable
});

var cursorPosition = 0;

$("#smsArea").on('keyup mouseup',function(e)
{
        cursorPosition = window.getSelection().getRangeAt(0);
 
 });

    
function makeDraggable() {
$(this).draggable();
}

function editTag(zoneId,tag)
{
var zoneDiv = document.getElementById(zoneId + 'Area');
var myButton = document.getElementById(zoneId + tag.ucfirst());
var myLabel = document.createElement('span');

var labels = zoneDiv.getElementsByTagName('span');
var spanSize= labels.length;

var delflag  = 0;
var delIndex = 0;

if(spanSize != 0)
{

for (myLabId = 0; myLabId < spanSize; myLabId++)
{
var currentLabel = labels[myLabId];
if(currentLabel.innerHTML === myButton.innerHTML)
{
delflag = 1;
delIndex = myLabId;
}
}
}

if(delflag == 1)
    {
        zoneDiv.removeChild(labels[delIndex]);
    }
else
{
myLabel.setAttribute('class', 'label label-info');
myLabel.setAttribute('data-effect', 'pop');
myLabel.setAttribute('contentEditable', 'false');
myLabel.setAttribute('style','cursor:move;font-size:100%;');
myLabel.setAttribute('name', tag);
    myLabel.setAttribute('draggable', 'true');
myLabel.innerHTML = myButton.innerHTML;

//zoneDiv.appendChild(myLabel);
    cursorPosition.insertNode(myLabel);
}

//Clean breaklines;
var bks = zoneDiv.getElementsByTagName('br');
var brSize = bks.length;

if(brSize != 0)
{
zoneDiv.removeChild(bks[0]);
}

//Event keyboard on deleted elements
$("span").dblclick(function(handler)
{
myLabel.remove(labels[delIndex]);
});

}

function saveMessage(zoneId)
{

var zoneDiv = document.getElementById(zoneId + 'Area');

var message = zoneDiv.childNodes; 
var messSize = message.length;
var messageContent = '';
console.log(message);
for (var messId = 0; messId < messSize; messId++)
{
var superRegex = /[a-zA-Z0-9áàâäãåçéèêëíìîïñóòôöõúùûüýÿæœÁÀÂÄÃÅÇÉÈÊËÍÌÎÏÑÓÒÔÖÕÚÙÛÜÝŸÆŒ._\s\.\,\--]/g;
if(zoneId === 'mail')
    {
superRegex = /[a-zA-Z0-9áàâäãåçéèêëíìîïñóòôöõúùûüýÿæœÁÀÂÄÃÅÇÉÈÊËÍÌÎÏÑÓÒÔÖÕÚÙÛ...

*/ Remaining code snippet removed for brevity /*

</body>
</html>
#smsArea {
  -moz-appearance: textfield-multiline;
  -webkit-appearance: textarea;
  height: 150px;
  overflow: auto;
  padding: 5px;
  resize: both;
  width: 100%;
} 

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

Utilizing Jquery for transmitting and receiving data

As a newcomer to application development, I have been struggling with figuring out how to send and retrieve data using the latest version of JQuery. My main concern is ensuring that the functionality I implement is compatible with all browsers. While I ha ...

What steps should I take to incorporate a timer into my bot similar to the timer used by other giveaway bots

I am looking to add a timer to my bot giveaway embed message that continues to update itself even when the bot is offline, without showing that the message was edited. Here's what I currently have in my embed: const embed = new MessageEmbed(); ...

What could be the reason for the absence of the loading sign in Chrome, even though it appears when the code is run on Firefox?

I implemented a function to display a loading screen on my HTML page with Google Maps integration. However, when I called the function popUpLoadingScreen() and dismissLoadingScreen() to show and hide the loading message while rendering map markers, the loa ...

Issues with Bootstrap Modal Checkbox Functionality

Issue with Bootstrap modal checkbox functionality when the checkbox is selected The desired behavior is for the bootstrap modal popup to be triggered upon clicking the checkbox Bootstrap Version: 3.3.6 Jquery Version: 2.1.3 $(function() { $(&ap ...

Position the label to the right and left of the input field for alignment

I've been struggling to create an input form with labeled using a dl, dt, dd list. I want the first label on the left, the second on the right, and the input in the center. However, no matter what I try, I can't get the second label to align corr ...

Sharing an object reference outside of a handler, for example, by making it accessible globally

I'm curious about best practices regarding passing references of the socket object outside of a method handler. In the code snippet below, can anyone provide guidance on how to achieve this? io.on('connection', function (socket) { co ...

Interactive cascading dropdown selection with ajax and jquery

I'm currently working on setting up a search feature with Dynamic dependent dropdown selection. The first dropdown menu fetches all the regions from the database, and the second one displays the cities corresponding to the selected region. However, I ...

When trying to import the Editor from draft-js-plugins-editor in a blank project, it results in TypeErrors

I recently started a new React project in Webstorm and added draft-js, draft-js-plugins-editor, draft-js-hashtag-plugin, and draft-js-mathjax-plugin using node modules. Following the instructions provided in the 'getting started' section on thei ...

Ensure that the column remains positioned to the right side of the page (float-right)

https://i.sstatic.net/TBjL6.png I am facing an issue with a three-column layout in one row. Each column is lg-6, but the last column ends up below the other two columns when there is more content in Column 2 than Column 1. The last column (Column 3) is flo ...

Passing variables with AngularJS and Typescript using a service

Currently in the process of developing an application using AngularJS, I am faced with the challenge of passing a URL when clicking on a menu button in order to utilize that URL within an iframe on another view controlled by a separate controller. Despite ...

Include IE-specific stylesheet code in your Angular application (version 1.2)

I would like to implement conditional IE CSS for IE8 and IE9 in my Angular application. The approach I took was to add the specific CSS files directly in the index file as shown below: <!-- Application main stylesheet --> <link href="styles/them ...

What is the best way to include a character in a string if there are no instances of the same character already present?

Looking for help with a function that can determine if a string contains a period and add one if it doesn't. So far, I'm struggling to make it either continuously add periods or not add any at all. function checkPeriod() { if (inputString.indexO ...

PHP and AJAX: Dual AJAX responses without synchronization

Hey there, I have an ajax-POST request from the client asking for specific information. My idea is to have a PHP file quickly respond with just a number and then follow up with a more time-consuming task that returns an array. I'm curious if it' ...

Selector matching a descendant element in React styling

I am facing a challenge with using the direct descendant CSS selector within a React inline style element: <style>{` .something>div{ color: blue; } `}</style> While this works fine in development, in production React replaces > ...

Turning select2 array output into a single string: a step-by-step guide

Is there a way to convert the output of select2 array into a single string separated by commas, like "task_owner":"Administrator,abc2", instead of having it as a single array like "task_owner":["Administrator","abc2"]? This is because the DB receives strin ...

Obtain data attributes using JQuery's click event handler

I'm facing an issue with a div structure setup as follows: <div class='bar'> <div class='contents'> <div class='element' data-big='join'>JOIN ME</div> <div class=& ...

What is the method for executing PHP code without the need for users to access the webpage?

Similar Query: Optimal method for running a PHP script on a schedule? I am in need of a solution where a PHP script can consistently fetch data from a single website, store it in a database on the server, and then update multiple other websites. The c ...

From PHP to Drupal Node with HTML transformations

Currently, I am developing a custom module on Drupal. Within this module, I have a requirement where users should be able to upload a PDF file. Once uploaded, the module should create a Node of type 'decision.' In the 'field_decision_text&ap ...

Several A-frames with a variety of animations

Is there a way to apply multiple animations to one object in A-frame? My goal is to make a gltf model move 5 spaces backwards, and then five spaces to the left once the initial animation is finished. How can I accomplish this task? ...

Deactivate the BACKSPACE button

Similar Question: How to disable backspace except textbox using jQuery I am looking for a solution to prevent the BACKSPACE button from functioning unless it is within a TEXT field. Although I have tried the code below, it ends up disabling the backs ...