PDA

View Full Version : Creating div's on the fly



Beth
06-09-2008, 11:29 PM
Hi everyone!

I'm trying to create a form that when a user enters text and presses the button the text appears on the page and the user is able to drag the text around. The code below which uses a Dynamic Drive drag script achieves this but I want to create a new div everytime the button is pressed so that the new text is separately draggable. Is this possible? My existing code (highlighted) just overtypes the previous text. I'd really appreciate any help.


<html>
<head>

<style type="text/css">
.drag{
position:relative;
cursor:move;
z-index: 100;
}
</style>

<script type="text/javascript">
/***********************************************
* Drag and Drop Script: Dynamic Drive http://www.dynamicdrive.com
* This notice MUST stay intact for legal use
* Visit http://www.dynamicdrive.com/ for this script and 100s more.
***********************************************/

var dragobject={
z: 0, x: 0, y: 0, offsetx : null, offsety : null, targetobj : null, dragapproved : 0,
initialize:function(){
document.onmousedown=this.drag
document.onmouseup=function(){this.dragapproved=0}
},
drag:function(e){
var evtobj=window.event? window.event : e
this.targetobj=window.event? event.srcElement : e.target
if (this.targetobj.className=="drag"){
this.dragapproved=1
if (isNaN(parseInt(this.targetobj.style.left))){this.targetobj.style.left=0}
if (isNaN(parseInt(this.targetobj.style.top))){this.targetobj.style.top=0}
this.offsetx=parseInt(this.targetobj.style.left)
this.offsety=parseInt(this.targetobj.style.top)
this.x=evtobj.clientX
this.y=evtobj.clientY
if (evtobj.preventDefault)
evtobj.preventDefault()
document.onmousemove=dragobject.moveit
}
},
moveit:function(e){
var evtobj=window.event? window.event : e
if (this.dragapproved==1){
this.targetobj.style.left=this.offsetx+evtobj.clientX-this.x+"px"
this.targetobj.style.top=this.offsety+evtobj.clientY-this.y+"px"
return false
}
}
}

dragobject.initialize()
</script>

<script type="text/javascript">

function sendtoDiv(){
document.getElementById("divbox").innerHTML = document.getElementById("input").value;
document.createElement('divbox'); document.body.appendChild();
}

</script>

</head>
<body>

<input type="text" id="input">
<input type="button" onClick="sendtoDiv();" value="Create">
<div class="drag" id="divbox"></div>

</body>
</html>

rangana
06-10-2008, 01:03 AM
You mean something like this:


function sendtoDiv(){
var k=document.createElement('div');
var val=document.getElementById("input").value;
k.innerHTML=val;
k.setAttribute('class','drag');
document.body.appendChild(k);
}

Beth
06-10-2008, 07:15 AM
Yes! That's awesome rangana! Thanks so much! In your example I don't even really need the <div class="drag" id="divbox"></div> hardwritten now. Thanks again! :)