Effortlessly move and place items across different browser windows or tabs

Created a code snippet for enabling drag and drop functionality of elements within the same window, which is working smoothly.

var currentDragElement = null;
var draggableElements = document.querySelectorAll('[draggable="true"]');


[].forEach.call(draggableElements, function(element) {
    element.addEventListener('dragstart', handleDragStart, false);
    element.addEventListener('dragenter', handleDragEnter, false);
    element.addEventListener('dragover', handleDragOver, false);
    element.addEventListener('dragleave', handleDragLeave, false);
    element.addEventListener('drop', handleDrop, false);
    element.addEventListener('dragend', handleDragEnd, false);
});

function handleDragStart(event) {
    currentDragElement = event.target;
    event.dataTransfer.setData("text/plain", event.target.dataset.uuid);
}


function handleDragOver(event) {
    event.preventDefault();

    event.dataTransfer.dropEffect = 'move';
    return false;
}

function handleDragEnter(event) {
    this.classList.add('over');
}

function handleDragLeave(event) {
    this.classList.remove('over');
}

function handleDrop(event) {
    event.stopPropagation();
    event.preventDefault();

    if(currentDragElement == event.target) {
        return;
    }

    console.log('dragged element ', currentDragElement.dataset.uuid , ' on element ', event.target.dataset.uuid)

    return false;
}

function handleDragEnd(event) {
    [].forEach.call(draggableElements, function (element) {
        element.classList.remove('over');
    });
}
section {
    border: solid 5px green;
    margin: 20px;
    float: left;
    width: 40%;
}

[draggable="true"]:hover {
    opacity: 0.6;
}

[draggable="true"] {
    cursor: move;
    background-color: #acacac;
    padding: 10px;
    margin: 10px;
}

.over[draggable="true"] {
    background-color: orange;
}
<section>
    <div draggable="true" data-uuid="1.1">draggable 1.1</div>
    <div draggable="true" data-uuid="1.2">draggable 1.2</div>
    <div draggable="true" data-uuid="1.3">draggable 1.3</div>
</section>

<section>
    <div draggable="true" data-uuid="2.1">draggable 2.1</div>
    <div draggable="true" data-uuid="2.2">draggable 2.2</div>
    <div draggable="true" data-uuid="2.3">draggable 2.3</div>
</section>

However, I am aiming to extend this feature by allowing users to drag and drop the draggable="true" elements between two separate windows or tabs in the same browser session.

The current implementation does not support this functionality because:

var currentDragElement = null;

remains null when dragging from another window/tab. My question is, how can I capture the drag start element even if initiated from a different window or tab within the same browser session? The goal is to have the console display the same information regardless of whether the drag and drop occurs within the same window or across different windows.

Kindly refrain from providing solutions using jQuery, thank you for your assistance!

Answer №1

It was @Mouser who highlighted that using local storage can achieve the desired outcome without any need for Ajax requests or similar methods.

This method was specifically tested in Google Chrome only.

Unfortunately, the use of local storage is not allowed in Stack Overflow fiddles. However, if you wish to experiment with this, simply copy the following code snippet, save it as an HTML file, open it in two browser windows, and enjoy playing around with drag and drop functionality:

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8>
    <title>drag - drop - demo</title>
    <style>

        section {
            border: solid 5px green;
            margin: 20px;
            float: left;
            width: 40%;
        }

        [draggable="true"]:hover {
            opacity: 0.6;
        }

        [draggable="true"] {
            cursor: move;
            background-color: #acacac;
            padding: 10px;
            margin: 10px;
        }

        .over[draggable="true"] {
            background-color: orange;
        }

    </style>
</head>
<body>

<section>
    <div draggable="true" data-uuid="1.1">draggable 1.1</div>
    <div draggable="true" data-uuid="1.2">draggable 1.2</div>
    <div draggable="true" data-uuid="1.3">draggable 1.3</div>
    <div draggable="true" data-uuid="1.4">draggable 1.4</div>
    <div draggable="true" data-uuid="1.5">draggable 1.5</div>
</section>

<section>
    <div draggable="true" data-uuid="2.1">draggable 2.1</div>
    <div draggable="true" data-uuid="2.2">draggable 2.2</div>
    <div draggable="true" data-uuid="2.3">draggable 2.3</div>
    <div draggable="true" data-uuid="2.4">draggable 2.4</div>
    <div draggable="true" data-uuid="2.5">draggable 2.5</div>
</section>

<script>

    var draggableElements = document.querySelectorAll('[draggable="true"]');

    [].forEach.call(draggableElements, function(element) {
        element.addEventListener('dragstart', handleDragStart, false);
        element.addEventListener('dragenter', handleDragEnter, false);
        element.addEventListener('dragover', handleDragOver, false);
        element.addEventListener('dragleave', handleDragLeave, false);
        element.addEventListener('drop', handleDrop, false);
        element.addEventListener('dragend', handleDragEnd, false);
    });

    function handleDragStart(event) {
        localStorage.setItem('currentDragElement', event.target.dataset.uuid);
        event.dataTransfer.setData("text/plain", event.target.dataset.uuid);
    }


    function handleDragOver(event) {
        event.preventDefault();
        event.dataTransfer.dropEffect = 'move';
        return false;
    }

    function handleDragEnter(event) {
        this.classList.add('over');
    }

    function handleDragLeave(event) {
        this.classList.remove('over');
    }

    function handleDrop(event) {
        event.stopPropagation();
        event.preventDefault();

        if(localStorage.getItem('currentDragElement') == event.target.dataset.uuid) {
            return;
        }

        currentDragElement = document.querySelector('[data-uuid="'+localStorage.getItem('currentDragElement')+'"]');

        console.log('dragged element ', currentDragElement , ' on element ', event.target)

        localStorage.setItem('currentDragElement', null);

        return false;
    }

    function handleDragEnd(event) {
        [].forEach.call(draggableElements, function (element) {
            element.classList.remove('over');
        });
    }


</script>

</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

Tips for enabling animation for AmCharts animateData feature

To achieve a real-time values per minute chart, the last bar value is to be incremented every minute after its addition. Additionally, a new bar with a value of 1 will be added each minute while removing the oldest bar. All these changes need to be animat ...

Basic mathematical operation utilizing a JQuery duplication event

Every time a new row is created, I want txtA divided by txtB to equal txtC. Please input the solution for textfield C. <table> <tr> <td><input type="text" id="txtA" name="txtA"></td> <td><input type="text" id ...

Unable to locate properties "offsetHeight" or "clientHeight" within a React/Next.js project developed in TypeScript

I have a unique customized collapsible FAQ feature that adjusts its height based on whether it's expanded or collapsed. import { useState, useRef, useEffect } from "react"; export default FAQItem({title, description}: FAQItemProps) { cons ...

Javascript is handling the JSON Request flawlessly, however, when using Nodejs, an error is encountered with a status

I'm trying to fetch a simple JSON File in NodeJS. Using Javascript and jQuery, it functions perfectly: $(document).ready(function() { $.getJSON('https://www.younow.com/php/api/broadcast/info/curId=0/user=Peter', function(json) { if ...

Replacing HTML text with JSON data can be easily achieved by using JavaScript

After receiving data from an API and converting it into JSON format, I encountered difficulty when attempting to change a selected element in HTML. Every time I tried to do so, I either got 'undefined' or 'Object Object' as the output. ...

What steps should be taken to address IE6 problems when a website functions properly in other browsers?

If you come across a website that functions perfectly on all browsers except for IE6, where the layout is extremely distorted but rebuilding the entire markup is not an option. Furthermore, only CSS selectors supported by IE6 are being utilized on the sit ...

Having trouble with jQuery div height expansion not functioning properly?

Having a bit of trouble with my jQuery. Trying to make a div element expand in height but can't seem to get it right. Here's the script I'm using: <script> $('.button').click(function(){ $('#footer_container').anim ...

The default value of the input color in HTML/NextJS does not update when changed

Issue: The color input does not change when the default value (#ffffff) is declared. https://i.sstatic.net/BpqUj.png However, it works normally if I don't declare a default value. https://i.sstatic.net/0dBd6.png Note: Using NextJS framework. <i ...

Interact with a dropdown menu using Selenium

Typically, my approach with the Selenium Select object is as follows: val selectCode = new Select(driver.findElement(By.id("someID"))) selectCode.selectByValue("4") The issue arises when there is no value in the html code. Here is an example of a ...

The Angular app.component.html is failing to display the newly added component

Having some trouble rendering my new component in the browser. I've set up a fresh project using the Angular CLI and created a component named list-employees. Upon running ng serve -o, the project compiles without errors, but the browser displays a b ...

The issue of memory leakage caused by jQuery Ajax requests

A problem has arisen on my website where memory is being leaked in both IE8 and Firefox. The Windows Process Explorer shows a continuous growth in memory usage over time. The issue arises when the page requests the "unplanned.json" URL, which is a static ...

Contrast between the act of passing arguments and using apply with arguments

I have an important backbone collection that utilizes a save mixin to perform Bulk save operations (as Backbone does not natively support this feature). // Example usage of Cars collection define([ 'Car', 'BulkSave' ], function(Car ...

Adaptive search bar and components housed within a casing

I am struggling to create a responsive box with a search feature for a mobile website. My plan is to incorporate jquery functions into the site, so I need to design an outer container that will house a distinct logo and search bar. However, when I test thi ...

Executing simultaneous asynchronous queries with Mongoose results in an error: `SyntaxError: Illegal return statement` due to

My goal is to make multiple asynchronous requests to Mongo using Mongoose in parallel. To achieve this, I created a helper function that handles these queries dynamically without knowing the exact number beforehand. While my current implementation works ...

What is the significance of using $timeout in order to activate a watch function?

There is an interesting phenomenon happening with my directive. It watches the height of an element that is being updated by a controller using a factory method to retrieve data. Strangely, unless I include a $timeout in that factory function, my watch doe ...

Secure access to an API using a certificate within a Vue.js application running on localhost

My vue.js app is built using vue-cli. The application is hosted at dev.example.com and the REST API can be found at dev.example.com/api/v1/. The backend has added an SSL certificate for security on the development environment. However, when I try to make a ...

Using CSS to customize the appearance of the preview in CKEditor

After successfully integrating CKEditor into my website CMS, I am facing an issue with the Preview button not using stylesheets (CSS). Despite editing the preview.html file located in: Website/ckeditor/plugins/preview/ It appears that the CSS is being ig ...

Creating a sidebar navigation in HTML and CSS to easily navigate to specific sections on a webpage

Here's a visual representation of my question I'm interested in creating a feature where scrolling will display dots indicating the current position on the page, allowing users to click on them to navigate to specific sections. How can I achieve ...

How to retrieve headers using Express.js middleware

My middleware creates authentication API keys that are then added to the header. const loger = require("easy-loger"); require('dotenv').config(); function authMiddleware(req, res, next){ const appApiKey = process.env.API_KEY; l ...

Adjusting Image Dimensions in jsPDF when Converting HTML to PDF

I have been experiencing some issues with image sizes while using jsPDF to convert HTML to PDF. I am currently on version 1.3.4 of jsPDF and below is the code snippet for reference: const tempElement = document.createElement("div"); tempElement. ...