CuriousMinds123
CuriousMinds123

Reputation: 21

HTML/JavaScript drag-and-drop but change the text DURING the dragging?

I've created a simple html webpage. Users need to select text like 1.23, and drag/drop it into another browser. That all works perfectly. (I didn't need to write ANY code in order to get that to work. I assume that's all part of the browser's built-in features.)

I need to round off that number to 1.5. I have NO trouble doing the rounding, but how can I catch (and change) the value during the dragging? I don't want to change the value in the first browser, it needs to stay as 1.23... I only need to do the rounding between the drag-start and the dropping, into the 2nd browser window.

Can that be done? I would post some code, but like I said this all works without any code... except for the "change while dragging part".

I'd rather write my own code and not drag in massive code libraries like jquery just for this 1 tiny feature.

Upvotes: 2

Views: 3622

Answers (2)

Michael B.
Michael B.

Reputation: 995

Use the dragstart and change the dataTransfer in it:

elem.addEventListener('dragstart', (evt) => {
    // get selected value
    const selectedValue = evt.dataTransfer.getData('text/plain')
    
    // check that really a number
    if(isNaN(Number(selectedValue))) return

    // set data transfer with new value
    evt.dataTransfer.setData('text/plain', Math.round(Number(selectedValue)).toString())
})

See other recommendation on dataTransfr on MDN for dataTransfer changing.

Upvotes: 0

Dom Slee
Dom Slee

Reputation: 611

Maybe you could try changing the text in the browser when it starts and reverting it back after you've dropped it? Try something like this:

https://jsfiddle.net/Domination/4zejjygk/1/

HTML:

<div id="dragEl" draggable='true'>1.5343</div>

JS:

//This is the element
dragItem = document.getElementById("dragEl");

//This is the event that changes it when mouse is over
dragItem.addEventListener("mouseover", HandleStart);

//These are events that change it back when the dragging is finished
dragItem.addEventListener("mouseout", HandleEnd);
dragItem.addEventListener("dragend", HandleEnd);
temp = dragItem.innerHTML;

//This is launched when it is hovered over
function HandleStart(e){
    e.preventDefault();
    text = e.target.innerHTML
    rounded = Math.round(Number(text)*10)/10; //Rounds the number to two decimal places
    e.target.innerHTML = rounded; 
}

//This is launched when dragging has finished
function HandleEnd(e) {
    e.preventDefault();
    e.target.innerHTML = temp; //Reverts to original
}

If you have access to the other page you are dragging it to, you could do as Ivan suggested and use the ondrop event on the section you are dropping it on...

https://jsfiddle.net/Domination/tgy7xgvx/1/

Upvotes: 1

Related Questions