Search code examples
javascripthtmldrag-and-droppositionpng

Draggable object coming back to top left


I'm using two draggable objects on my personal website, and it's perfectly moving. The only problem is that when I drag it for the first time, it comes back to the top left... I have the feeling it's doing this because i'm using % for the position...

My website : arnaudaubry.info

Here is my code for drag and drop:

<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>

Here is my code for the image :

<img src="http://arnaudaubry.info/wp-content/uploads/2016/11/drag_lookingforwork-03.png" style="position:fixed;    top:70%; left:75%; width:11%;" class="drag">


Solution

  • Change this lines:

    this.offsetx=parseInt(this.targetobj.style.left)
    this.offsety=parseInt(this.targetobj.style.top)
    

    to

    this.offsetx=this.targetobj.offsetLeft;
    this.offsety=this.targetobj.offsetTop;