How come I am encountering an Uncaught TypeError when attempting to execute 'appendChild' on 'Node' with this draggable code?

I have been working on incorporating this code snippet from Web Dev Simplified into my project:

JS:

const draggables = document.querySelectorAll('.draggable')
const containers = document.querySelectorAll('.drag-container')

draggables.forEach(draggable => {
    draggable.addEventListener('dragstart', () => {
        draggable.classList.add('dragging')
    })

    draggable.addEventListener('dragend', () => {
        draggable.classList.remove('dragging')
    })
})

containers.forEach(container => {
    container.addEventListener('dragover', e => {
        e.preventDefault()
        const afterElement = getDragAfterElement(container, e.clientY)
        const draggable = document.querySelector('.dragging')
        if (afterElement == null) {
            container.appendChild(draggable)
        } else {
            container.insertBefore(draggable, afterElement)
        }
    })
})

function getDragAfterElement(container, y) {
    const draggableElements = [...container.querySelectorAll('.draggable:not(.dragging)')]

    return draggableElements.reduce((closest, child) => {
        const box = child.getBoundingClientRect()
        const offset = y - box.top - box.height / 2
        if (offset < 0 && offset > closest.offset) {
            return { offset: offset, element: child }
        } else {
            return closest
        }
    }, { offset: Number.NEGATIVE_INFINITY }).element
}

CSS:

.drag-container {
    background-color: #333;
    padding: 1rem;
    margin-top: 1rem;
}

.draggable {
    padding: 1rem;
    background-color: white;
    border: 1px solid black;
    cursor: move;
}

    .draggable.dragging {
        opacity: .5;
    }

Despite spending most of my time with C# for the backend, I decided to try out some frontend JS by implementing the above code. However, I'm facing issues as it doesn't seem to work seamlessly with my existing code that previews images before uploading:

function previewImages() {

    let aux = document.getElementById("preview-multiple");

    if (aux.hasChildNodes()) {

    while (aux.firstChild) {
        aux.removeChild(aux.firstChild);
        }

    }


    if (this.files) {
        [].forEach.call(this.files, readAndPreview);
    }

    function readAndPreview(file) {

        if (!/\.(jpe?g|png|gif)$/i.test(file.name)) {
            return alert(file.name + " is not an image");
        } 

        var div = document.createElement('div');
        var reader = new FileReader();

        reader.addEventListener("load", function () {
            var image = new Image();
            image.height = 100;
            image.title = file.name;
            image.src = this.result;
            image.className = "draggable";
            image.draggable = true;
            //draggable.js dependent of previewImage.js
            aux.appendChild(div);
            div.appendChild(image)
        });

        reader.readAsDataURL(file);

    }

}

In my image preview code, I specifically added:

image.className = "draggable";
            image.draggable = true;

to enable dragging functionality and organized them within divs for better structure.

However, encountering errors when attempting to drag the images has left me baffled:

https://i.sstatic.net/tXJJF.png

I am unsure where I may be going wrong in my implementation.

My next challenge includes saving these images in a database with ordering based on the View, but that's a task for another day.

Do you have any insights or solutions to offer? Thank you.

Answer №1

After some investigation, I have identified the root cause. The issue stemmed from the script executing before the images were properly loaded into the document object model.

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

Error: The array index is outside the permissible range

Can someone assist me in understanding the cause of this error? IndexOutOfRangeException: Array index is out of range. (at Assets/Scripts/PlayerCar.js:73) CompareApproximately (det, 1.0F, .005f) UnityEditor.DockArea:OnGUI() Snippet from My code: var Gea ...

Get rid of any type of encoding or default encoding that may be applied to a jQuery ajax call

Is it possible to completely remove all types of encoding, including default encoding, on a jQuery AJAX call? Here is an example JavaScript code: function callServer() { debugger; var uncompressed64Data = "/9j/4AAQSkZJRgABAQEAYABgAAD/2 ...

Is there a way to halt AngularJs code for Bootstrap Confirmation Dialog?

Currently, I am in the process of updating old Style window.confirm dialogue boxes to use a Bootstrap Dialogue box. In order to achieve this, I have integrated a JavaScript function within an Angular code snippet as shown below: function showConfirmation( ...

ESLint is flagging an issue where the TypeScript type declaration is attempting to reference a type that

Currently, I am in the process of developing a builder that incorporates various types. The method I use to define the type is as follows: export type BuilderInterface<T> = { [key in keyof T]: (arg: T[key]) => BuilderInterface<T>; } & ...

Exploring render props, leveraging Apollo, and enhancing JSX props using arrow functions

There are numerous examples illustrating how to utilize Apollo, such as: <Mutation mutation={YOUR_MUTATION} update={(cache, { data }) => { // execute operations to update the Apollo store }} > { mutate => ( <UI m ...

Steps for displaying a loading image during the rendering of a drop-down list (but not during data loading):

Using jQuery's autocomplete combobox with a large dataset of around 1,000 items. The data loads smoothly from the server, but there is a delay when expanding the drop-down list to render on screen. Is there a way to capture the initial click event on ...

Having trouble with the lodash find function in my Angular application

npm install lodash npm install @types/lodash ng serve import { find, upperCase } from 'lodash'; console.log(upperCase('test')); // 'TEST' console.log(find(items, ['id', id])) // TypeError: "Object(...)(...) is un ...

a guide to structuring REST API requests with axios in Vue.js

In my Vue.js app, I am utilizing Axios to consume a REST API. Each time I make an API call, I create a new instance of Axios with the necessary authentication headers by calling axios.get in various places. // UserdataComponent.vue const anInstance = axio ...

Tips for creating a nodeCategoryProperty function for a TypeScript Model:

nodeCategoryProperty function has a signature requirement of (a: ObjectData, b?: string) => string. In my opinion, this should be updated to (a: ObjectData, b?: string) => string | void, as the function is intended to not return anything if used as a ...

Is it possible to modify a portion of the zod schema object according to the value of a

My form consists of several fields and a switch component that toggles the visibility of certain parts of the form, as shown below: <Field name="field1" value={value1} /> <Field name="field2" value={value2} /> &l ...

Does the round function always produce the most accurate floating point approximation?

Will the result of using round(3.12143345454353,2) always be equivalent to simply using the literal value 3.12? The floating point approximation would suggest so (3.12000000000000010658141036401502788066864013671875). In simpler terms, can we rely on the ...

Issue with firing events from a button located within a templated control

I am encountering an issue with triggering events from within my templated control. Although my actual control is more complex and includes additional templates, the core structure is similar to this: <MyControl> <SomeTemplate> &l ...

Issue with ESlint global installation in macOS root terminal

Having trouble installing ESlint globally on my Mac running Mojave 10.14.6. Every time I try to run 'npm install -g eslint' I keep encountering this error: Your operating system has rejected the operation. npm ERR! It seems that you lack the nec ...

Show information from a JSON file in a grid layout using .NET

I recently developed a simple Shopify app to retrieve product details. After accessing the code from GitHub, it successfully displayed the product details in a text box. Now, I want to make a simple change to show the product details in a grid view. Bel ...

Tips for stopping a Node.js for loop if it runs for more than 20 seconds

Imagine a situation where I have a for loop performing some actions, and I want to terminate the loop if it takes longer than 20 seconds to complete. async function mainFunc(){ for (let step = 0; step < 5; step++) { // Executes a complex op ...

What new approach should I take now that interceptBufferProtocol is outdated in order to use protocol.handle for intercepting both http and https requests

While working on my electron application, I wanted to implement a captcha harvester pop-up window. Upon searching, I found a git repository that seemed promising: https://github.com/sashapisdets/Captcha-Solver. After cloning it, I realized that it worked p ...

Pass the most recent properties to the mousemove event handler

I am currently developing a click-and-drag feature, which involves: setting up a moveListener on the onMouseDown event having the moveListener trigger an action that updates certain props of the component (props.whichChange) cleaning up the mouseUp event ...

Having Trouble Showing Loading Component on Next.js v13

Having some issues with setting up a loading component in my Next.js v13 project. I followed the documentation by creating a file called loading.tsx in the src directory, but it's not appearing on the page as expected. I've also included a functi ...

Introducing a fresh counter variable inside a for loop

I'm currently working on a project with google-apps-script. My goal is to copy a row multiple times based on the number specified in a certain cell within a spreadsheet. For example, if B2 contains the number 6, I want to duplicate that row 6 times. I ...

"Challenges with SignalR's compatibility with IE9's back and forward

While developing an intranet portal using Asp.net MVC, I incorporated the SignalR library for interactivity. However, I encountered a strange issue while navigating site pages. Occasionally, when attempting to use the "back" or "forward" buttons in Inter ...