Upon clicking on one of the rounded rectangles in the following code, it is required to create a copy of the span element and place it on top of the original element. The code does that, but the new element has an increased height. Please suggest what could go wrong.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<div id="phrasesDiv" style="line-height:250%" /></div>
<style type="text/css">
.phrase {
font-size:18pt;
color:blue;
background: palegreen;
border:2px solid green;
padding:2px 10px 2px 10px;
-webkit-border-radius:10px;
}
</style>
<script type="text/javascript">
{
// create the phrase list dynamically
var phraseList = "Apple~Orange~Kiwi~Guava";
var phrasesDiv = document.getElementById("phrasesDiv");
var phrases = phraseList.split('~');
for (var i=0; i<phrases.length; i++)
phrasesDiv.innerHTML += "<span id=\""+phrases[i]+"\" class=\"phrase\" onmousedown=\"phraseTouched('"+phrases[i]+"')\">"+phrases[i]+"</span> \n";
}
function getDim(el) {
var lw = el.offsetWidth;
var lh = el.offsetHeight;
for (var lx=0, ly=0; el != null; lx += el.offsetLeft, ly += el.offsetTop, el = el.offsetParent);
return {x:lx,y:ly,w:lw,h:lh};
}
function phraseTouched(id) {
var elem = document.getElementById(id);
var dim = getDim(elem);
var dragElem = document.createElement('span')
dragElem.id = id+"_copy";
dragElem.innerHTML = id;
dragElem.className += " phrase";
dragElem.style.background = "pink";
dragElem.style.position = "absolute";
dragElem.style.left = dim.x+"px";
dragElem.style.top = dim.y+"px";
elem.parentNode.appendChild(dragElem);
}
</script>
</html>
EDIT: The following function worked … but I am still curious to know why am I getting an increased height if I add to the div programatically.
function phraseTouched(id) {
var elem = document.getElementById(id);
var dim = getDim(elem);
document.body.innerHTML += "<span id=\"_"+id+"\" class=\"phraseDrag\" style=\"left:"+dim.x+"px;top:"+dim.y+"px;position:absolute;\">"+id+" </span>\n";
}
Simply put, you break out the standard layout model when you add that nasty “position: absolute” property to your element and it doesn’t know how to represent itself. If you want to maintain most of the styling, the easiest fix would be to simply add:
somewhere in your .phrase style, at least that’s what I would do.
Of course Vijay’s solution works as well as long as you don’t mind losing that line-height property.