positioning newly generated dropped elements within the DOM structure dynamically

Hello everyone, I have a query related to drag and drop functionality. I am currently working on an application that allows users to create websites using only drag and drop features. I am facing a challenge in implementing a feature where users can drop elements at specific positions and the elements below the dropped element automatically shift down. The issue arises from dynamically generated elements. For example, in the right panel, there are various components displayed as images. When these elements are dragged, certain meta-data is passed along. Upon dropping the element, an HTML element is created based on this meta-data.

<div class="drop-zone">
   <div>
     <!--container 1-->
   </div>
     <!-- here I want to drop the dynamically generated element -->
   <div>
     <!--container 2-->
   </div>
</div>

*****************EDIT*****************************

The 'header drop' directive in the code snippet below is used for dragging, while JSONfn serves to stringify functions within JSON objects.

(function(){
define(['../../../../app','./../service/header.factory.js'],function(app){
    app.directive('headerDrop',['HeaderFactory',function(HeaderFactory){
        return {
            restrict: "E",
            replace: false,
            scope: {},
            link: function(scope,element,attrs) {
                element.on('dragstart',function(e){
                   e.originalEvent.dataTransfer.setData("data",JSONfn.stringify(HeaderFactory));
                });
            },
            template: "<img id='header' draggable='true' src='/src/create_template/images/noimage.jpg' width='100' height='100'> </img>"
        }
    }]);
    app.directive('dragContainer',function(){
        return {
            restrict: "E",
            replace: false,
            scope: {},
            template: "<div id='elements-container'> <h1 style='text-align:center;'> All </h1><header-drop> </header-drop> </div>"
        }
    });
});

})()

Within the controller:

element.on('drop',function(event){
        console.log(event);
        if(event.target.className !== "drop-zone"){
            event.preventDefault();
            return false;
        }
        var data = JSONfn.parse(event.originalEvent.dataTransfer.getData("data"));
        if(data.type=="header"){
            var heading = document.createElement("h1");
            console.log("client height" , heading.clientWidth);
            heading.innerHTML = data.textValue;
            heading.style.position = "relative";
            heading.style.top = ((event.pageY/window.innerHeight)*100)+ "%";
            heading.className = "editable";
            event.target.appendChild(heading);
            heading.style.top = event.clientY;
            addingEvents();
        }
    });

Answer №1

While initially taking on this problem, I approached it naively but eventually discovered the solution.

I was working on a template generator, and this method ended up being effective for me.

Original Naive Approach

My initial strategy involved dropping an extra block inside the designer with a height of 5px just above the element, like so:

<div class="adjacent-block"> </div> inside css .adjacent-block {min-height: 5px; }
<div class="dropped-block"> </div>

Then, I would place the element inside the adjacent block.

Drawback: You also have to keep track of the adjacent block.

I DO NOT RECOMMEND THE ABOVE METHOD AS IT WAS INEFFECTIVE

A SIMPLER AND MORE EFFECTIVE APPROACH:

In the dragover event, simply check if the element is positioned above another element and drop the block before or after the element based on the mouse's position relative to the middle of that element.

I have not yet tried this approach, but I am confident that it will be successful.

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

Parse a string containing a selection of markdown by using regular expressions for tokenization

I need to tokenize a string using a regular expression that consists of markdown formatting. Specifically, bold text is denoted by **text** and italic text is denoted by _text_. To tokenize the string "a _b_ c **d** _e", it should be split into ['a & ...

PHP prepared statements do not seem to be effectively updating or inserting entire datasets

My website allows members to create and update posts using a text editor. However, I've run into an issue when the post content includes new lines or spaces such as <p>&nbsp;</p> or <div>&nbsp;</div>. The problem arises ...

What is the best way to implement a personalized hook in React that will return the number of times a specific key is pressed?

I'm working on a custom hook that should give me the key pressed, but I've noticed that when I press the same key more than twice, it only registers twice. Here's my code: import { useEffect, useState } from "react" function useKe ...

Optimal Timing for Loading Initial State from Database Using Vuex

In my Vue/Vuex project, I have a simple setup where I retrieve a list of categories from my database using an HTTP GET request. Before implementing Vuex, I used to fetch this data directly in my main component when it was created. Now with Vuex, I have g ...

Storing and retrieving data on a webpage using JQuery: A beginner's guide

I have a set of data that I'll display on a webpage using PHP, and I want JQuery to be able to process it. However, I prefer the data not to be visible to the user. Here's an example: <div id="data-1"> <span id="width">5</span ...

Sending an additional parameter to a callback function

I am currently working on enhancing the functionality of my custom logging system for DB operations. My goal is to generate a more visually appealing and organized format in the console by adding an additional variable called operationName to the log messa ...

Using AJAX to submit a form and retrieve response data in Javascript

After successfully getting everything to post correctly, I encountered a problem with this script. It keeps loading the content into a new page. Could it be related to the way my php file returns it using "echo(json_encode($return_receipt));"? <s ...

My approach to using this style in React involves utilizing the class attribute as follows: "class[attribute]" [Updated version 2]

When trying to customize an element based on its attribute, the process is a bit different in React compared to pure CSS. Here's an example: <div class='something' data-test='4'></div> ... .something[data-test] { bac ...

The Jquery image on.load event seems to only function properly after performing a manual hard refresh of

Looking for a solution to replace loading text with a button only after the image has loaded onto the page. Utilizing on.load as follows: $('img.house').on('load', function() { $('.loading').hide(); $('# ...

Issues with integrating the jsPDF package into a JavaScript project

I'm struggling to solve this issue. I've been attempting to create a program that can download a pdf from a webpage using the jsPDF npm module. After downloading it, I tried importing it in two different ways: Using the node.js require statemen ...

What steps should be taken to gain access to the FormController if the form is contained within a directive?

Here is the code for my custom directive: restrict: 'E', scope: { }, templateUrl: 'directives/my.directive.html', link: function(scope) { // I want to be able to access "myForm" here (e.g., to setPristine(), etc.) scope.custom ...

Vue - when multiple parents share a common child component

Is there a way in Vue.js for multiple parents to share the same child component? I am looking to have multiple delete buttons trigger a single modal with different content. For example: myfile.html: <table id="app" class="table table-striped table-s ...

What is the Best Way to Send JavaScript Variables to MYSQL Database with PHP?

I am having trouble sending my variable to a MySQL database. The database only displays the variable when using the HTML input tag. The error message I received was "Undefined index: rate & amount." Seeking assistance to resolve this issue. Thank you! ...

The "useState" React Hook is restricted from being used in a class component. To utilize React Hooks, they can only be invoked within a React function component or a custom React Hook function

I am relatively new to React frontend development and I am currently working on adding a temporary drawer to my Material-UI NavBar. Here is the code snippet where I added the drawer: class Navbar extends Component { render() { const { authentic ...

What is the best way to implement a Navbar link in React.js?

I am currently working on developing a website using Reactjs. I have successfully created a Navbar with two links - Home and Contact. However, when I click on the Contact link, although the URL changes accordingly, the page itself does not update. I have s ...

How does the Rx subscribe function maintain its context without the need to explicitly pass it along

Currently, I am utilizing Rx with Angular2 and making use of the Subscribe method. What intrigues me is that the callbacks of the method are able to retain the context of the component (or class) that initiated it without needing any explicit reference pas ...

What is the best way to prevent the body from scrolling when scrolling on a fixed div without making the body's scroll bar disappear?

Is there a way to prevent the body from scrolling while I scroll on a fixed div? I attempted using overflow:hidden for the body, which stops scrolling but causes the page to shake when the scroll bar disappears. Is there a solution that allows me to keep ...

How can I transform each word to resemble this format?

let sentence = "Hello+world + like+ this + name,bla"; sentence = sentence.replace(/\+\s\+/g, function(match){ return "*" + match.trim() + "*"; }); alert(sentence); // Output will be " *Hello*+*world*+like*+this*+name,*bla* "; How can I ...

Transform a date string into a date entity

Collecting the user's input for the date and saving it as a string variable. The format of the value is Fri Aug 27 2021 00:00:00 GMT+0530 (India Standard Time) My goal is to convert this string back into a new Date() object in order to make additiona ...

Tips for incorporating a pause or delay into if-else statements

Trying to optimize my semi-automated JavaScript code so it runs at a slower pace. Currently, it fetches detailed data from 100 listings one by one at a speed of around 15 times per second. While this works well in some aspects, it makes tracking which elem ...