Grab the inner html content of a specific element and release it into a different element by holding down the mouse button

I am working with a grid that has a start node. My goal is to make this node a draggable object without moving the HTML element itself, as it contains important information about that particular node (such as position and state). Instead, I only want to move the inner html of the node to another HTML element so that key data like x and y coordinates remain intact.

Here is the desired outcome:

https://i.sstatic.net/iPfEx.gif

What steps should I take to achieve this effect?

The current event handling function in place is as follows:

const events = () => {
  for (let i = 0; i < 16; i++) {
    for (let j = 0; j < 45; j++) {
      const node = board[i][j];
      node.DOMElement.addEventListener("click", function () {
          // Click events occur here for a specific Node at x and y positions on the board
      });
    }
  }
};

Answer №1

Success! I was able to solve the issue by making adjustments when the mouse enters or leaves the tile.

let isMouseDown: boolean = false;
let startNodeClicked: boolean = false;
let targetNodeClicked: boolean = false;

document.addEventListener("mousedown", () => {
  isMouseDown = true;
});

document.addEventListener("mouseup", () => {
  isMouseDown = false;
});

export const handleEvents = () => {
  for (let i = 0; i < 16; i++) {
    for (let j = 0; j < 45; j++) {
      const node: Node = board[i][j];
      const nodeElement: HTMLElement = board[i][j].DOMElement;

      nodeElement.addEventListener("mouseleave", () => {
        removeStartNodeOnDrag(node, nodeElement);
      });

      nodeElement.addEventListener("mouseenter", () => {
        addStartNodeOnDrag(node, nodeElement);
      });

      nodeElement.addEventListener("mouseleave", () => {
        removeTargetNodeOnDrag(node, nodeElement);
      });

      nodeElement.addEventListener("mouseenter", () => {
        addTargetNodeOnDrag(node, nodeElement);
      });
    }
  }
};

const removeStartNodeOnDrag = (node: Node, nodeElement: HTMLElement) => {
  if (node.type === "start" && isMouseDown) {
    nodeElement.classList.remove("start");
    node.type = "empty";
    node.state = "unvisited";
    startNodeClicked = true;
  }
};

const addStartNodeOnDrag = (node: Node, nodeElement: HTMLElement) => {
  if (node.type === "empty" && isMouseDown && startNodeClicked) {
    nodeElement.classList.add("start");
    node.type = "start";
    node.state = "visited";
    startNodeClicked = false;
  }
};

const removeTargetNodeOnDrag = (node: Node, nodeElement: HTMLElement) => {
  if (node.type === "target" && isMouseDown) {
    nodeElement.classList.remove("target");
    node.type = "empty";
    targetNodeClicked = true;
  }
};

const addTargetNodeOnDrag = (node: Node, nodeElement: HTMLElement) => {
  if (node.type === "empty" && isMouseDown && targetNodeClicked) {
    nodeElement.classList.add("target");
    node.type = "target";
    targetNodeClicked = false;
  }
};

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

Failure to recognize AJAX content in .ready function

When using an AJAX call to load content, primarily images, I encountered a challenge. I wanted the div to fade in only after all the images were fully loaded. To achieve this, I made use of .ready method in jQuery. However, it seemed like the images were n ...

Enhance your browsing experience with Fire-fox add-on that automatically triggers JavaScript after YouTube comments have

I am currently working on creating an add-on for the Firefox browser. I have implemented a page-mod that triggers a script when specific pages (such as Youtube) are loaded, allowing it to communicate data back to the main script. However, I am encountering ...

Error occurs consistently with AJAX, PHP, and SQL newsfeed

Striving for Progress Currently, I am engrossed in developing a newsfeed and enhancing my proficiency in utilizing Ajax through jQuery. My ultimate aim is to create a seamless user experience where individuals do not need to refresh the page to view the l ...

Three.JS: Utilizing a wireframe material for spheres with the EdgesHelper control

I'm exploring Three.JS for the first time and I have some doubts about whether it's the best tool for my current project. My goal is to create a wireframe material on a simple spherical geometry that looks like this: https://i.sstatic.net/WPfAh ...

Adjust the path-clip to properly fill the SVG

Is there a way to adjust the clip-path registration so that the line fills correctly along its path instead of top to bottom? Refer to the screenshots for an example. You can view the entire SVG and see how the animation works on codepen, where it is contr ...

How can Swiper efficiently display the next set of x slides?

After exploring SwiperJS at https://swiperjs.com/, I've been unable to locate an option that allows the slide to return immediately to the right once it goes out of view on the left. The current behavior poses a problem where there is no next slide o ...

The click event in jQuery is being blocked by the use of "display:none

Currently, I have implemented a search box feature with search suggestions: <input id="searchBar" /> <div id="searchSuggestion"></div> The searchSuggestion div is dynamically updated using jQuery ajax whenever an input is entered (imple ...

Experience a seamless transition as the background gently fades in and out alongside the captivating text carousel

I have a concept that involves three background images transitioning in and out every 5 seconds. Additionally, I am utilizing the native bootstrap carousel feature to slide text in synchronization with the changing background images. Solving the Issue ...

Challenges encountered while setting up Hotjar integration in Next.js using Typescript

I am encountering issues with initializing hotjar in my Next.js and TypeScript application using react-hotjar version 6.0.0. The steps I have taken so far are: In the file _app.tsx I have imported it using import { hotjar } from 'react-hotjar' ...

Wrapping an anonymous function in a wrapper function in Typescript can prevent the inferred typing

I am encountering an issue with typing while coding: function identity<T>(v: T): T{ return v; } function execute(fn: {(n: number):string}) {} execute((n) => { // type of n is 'number' return n.toFixed(); }) execute(identity(( ...

Dealing with a situation where different functions need to be called based on a condition while using unique button names. This is

<button type="button" class="btn btn-primary ms-4" (click)="update()">Save</button> <button type="button" class="btn btn-primary ms-4" (click)="create()">Add</button> B ...

Incorporate personalized buttons into the header navigation for each view using VueJS

In my VueJS project, I attempted to include custom buttons in the sub navigation menu which could be customized for each view. Initially, I tried adding a simple property to the main data element, but that didn't yield the desired results. Then, I cam ...

Nightwatch encounters difficulty in accessing the iframe element

While utilizing the xquery selector, I attempted to input a value into the iframe's input field, but unfortunately, my efforts were fruitless. `.frame('someid') .setValue('//input[contains(@name,"project name")]', 'Nig ...

Add a button feature to both upload and download a todo list within a JavaScript file, similar to a text file

I'm looking to enhance my simple todo list with a download and upload function. I want to be able to save the list in local storage and then upload or download it from a server code. Below is a link to my code: https://jsfiddle.net/zahrashokri/uqkn6t ...

Tips for importing and exporting icons in a way that allows for dynamic importing using a string parameter

I am facing an issue with dynamically importing SVG icons in React Native. Initially, I tried using the following code snippet: const icon = require(`@src/assets/icons/${iconName}`) However, after realizing that this approach wouldn't work for me, I ...

I am not enhancing the array's value; rather, I am substituting it

Hey everyone, I'm currently working on extracting an array of Sizes and Colors from an object. The goal is to trigger a handler, clickHandler(), when the input is clicked. However, each time the handler is invoked, the code ends up replacing the value ...

Leverage Vue's ability to assign data from a parent component to

I am struggling to bind the data (inputData) from the parent component to my child component. I have checked my code multiple times but cannot find where the mistake is. MainApp.js let vm = new Vue({ el: "#app", components: { &ap ...

Tips for optimizing the performance of a sine wave animation

After experimenting with JavaScript, I've managed to create a visually appealing sine wave animation but it's causing performance issues due to the high number of vectors being generated. My current setup involves utilizing the p5js library. Bel ...

Is it possible to send a Word file as an email attachment using PHP's mail() function

When I sent a Word document file via email, it generated an unknown format like asdfADFDF 0000sadfas15454454. The mail function was used to send the email. Below is the code for that. Please review and let me know: function sendfile() { $id = $_REQU ...

Issue with dropdown element not triggering JavaScript onchange event

I am in the process of developing an application that involves searching a database and enabling users to compare the results. To achieve this, I require multiple dependent drop-down menus. While I have some understanding of HTML and PHP, my coding experti ...