Victor Mehta Victor Mehta - 4 months ago 16
Javascript Question

How to write <div> code inside a HTML box without reloading the entire page

I have the following working code below that allows a math symbol (by using MathJax) displayed in the box on the left to be dragged onto the box on the right. But there are two problems. First, the symbol which is dragged from box on the left disappears from this left box which I don't want and secondly I need to be able to write

<div>
code in the drop() function (to display the math symbol) in box on the right in order to control the displaying of the symbol. I do not want the entire page to be refreshed only the contents within the box on the right. See working code here:



function allowDrop(ev) {
ev.preventDefault();
}

function drag(ev) {

ev.dataTransfer.setData("text", ev.target.id);
}

function drop(ev) {

// here is where I need to write <div> code but not sure how
// to start
ev.preventDefault();
var data = ev.dataTransfer.getData("text");
ev.target.appendChild(document.getElementById(data));
}

#header {
width: 100%;
background-color: white;
height: 30px;
}
#container {
width: 500px;
background-color: #ffffff;
margin: auto;
}
#first {
width: 100px;
border: 2px solid black;
float: left;
height: 300px;
}
#second {
width: 300px;
border: 2px solid black;
float: right;
height: 100px;
}
#clear {
clear: both;
}

<script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<div id="header"></div>
<div id="container">
<div id="first">
<span id="drag1" style="text-decoration:overline;" draggable="true" ondragstart="drag(event)">$$\sum$$</span>
<span id="drag2" style="text-decoration:overline;" draggable="true" ondragstart="drag(event)">$$\int$$</span>
<span id="drag3" style="text-decoration:overline;" draggable="true" ondragstart="drag(event)">$$\alpha$$</span>
<span id="drag4" style="text-decoration:overline;" draggable="true" ondragstart="drag(event)">$$\beta$$</span>
</div>
<div id="second" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<div id="clear"></div>
</div>




Answer

When you are dropping the box, you are actually MOVING it to a new parent. Just clone the drag item and append the new item

function drop(ev) {

    // here is where I need to write <div> code but not sure how 
    // to start
    ev.preventDefault();
    var id = ev.dataTransfer.getData("text");
    var el = document.getElementById(id).clone(true);
    el.id = ""; // remove the id
    ev.target.appendChild(el);
}

This will copy all the attributes and events, if all you need is the inner text you can simply create a new DOM element

function drag(ev) {
    ev.dataTransfer.setData("text", ev.target.innerText);
}
function drop(ev) {
    ev.preventDefault();
    var data = ev.dataTransfer.getData("text");

    // create new element from text
    var el = document.createElement("span");
    el.innerText = data;
    ev.target.appendChild(el);
}