It's been quite some time since this question was asked, but I encountered the same issue today and found it surprisingly difficult to change the cursor while dragging an element using JavaScript.
Despite trying various methods like using the dataTransfer
object, the dropEffect
property, and the dragEvent
event, none of them seemed to work for me, even after consulting the MDN Web Docs.
For those who are still struggling with changing the cursor during a drag operation, here's a solution that worked for me:
Key Point: Add a CSS class with pointer-events: none
to elements where you don't want the "not allowed" cursor to appear.
// Identify the container
const file_container = document.querySelector("#file_container")
// Grab all the files
const files = document.querySelectorAll("[data-id='file']")
// Loop through each file
for (let file of files)
{
// Initiate the file drag action
file.addEventListener("dragstart", (ev)=>{
ev.target.classList.add("ds_awaiting_file")
})
// Allow dropping by preventing the dragover event
file_container.addEventListener("dragover", (ev)=>{ev.preventDefault()})
// Remove the added styles from the awaiting file
document.addEventListener('dragend', ()=>{
file.classList.remove("ds_awaiting_file")
});
}
/* Solution for Problem - prevent pointer events on div children */
[data-id=file] *
{
pointer-events: none;
}
/* General Styling */
#file_container
{
display: grid;
grid-template-columns: 160px 160px 160px;
grid-template-rows: 100px;
grid-column-gap: 20px;
grid-row-gap: 20px;
}
[data-id=file]
{
border: 2px solid #1E3050;
padding: 12px 60px
}
.block
{
background-color: #1E3050;
height: 40px;
width: 40px;
}
.ds_awaiting_file
{
opacity: 0.3;
}
<div id="file_container">
<div data-id="file" draggable="true">
<div class="block"></div>
<p>File_1</p>
</div>
<div data-id="file" draggable="true">
<div class="block"></div>
<p>File_2</p>
</div>
<div data-id="file" draggable="true">
<div class="block"></div>
<p>File_3</p>
</div>
<div data-id="file" draggable="true">
<div class="block"></div>
<p>File_4</p>
</div>
</div>
This approach will help in hiding the "drag not allowed" cursor when dragging, however, please note that in certain browsers like Chrome and Opera, borders and margins might still be identified as non-allowed elements.