mklein 0 Newbie Poster

Dear forum

Rather than use a library, I have attempted to write my own attempt at a script that allows multiple elements to be dragged around the page. It starts by loading all divs into an array, and then forms a new array of only divs with the required class name. I believe this script doesn't work for internet explorer, but I am not concerned by this.

As you will see if you run the code below, the script works well for divs containing text, but if I include an image inside a div, then the image will follow the mouse even if the button is released.

I have spent a whole day on this tiny script and really don't know where to go from here! Could anybody shed some light on this please?

Thanks

Matt

<html> 
<head> 

<style> 
 .dragger 
 { 
  background-color:lightgreen; 
  position:absolute; 
 } 
</style> 

<script type="text/javascript"> 

var all_els=[]; 
var els=[]; 
var el; 

 window.onload = function() 
 { 

all_els=document.getElementsByTagName("div"); //an array of all div elements on page 
for(var i=0;i<all_els.length;i++){ 

if(all_els[i].className=='dragger') { els.push(all_els[i]);}   //just add those with the correct class name to our final array 

 } 


  for (el in els) 
  { 
  this.dragging=false;  //each element in the array is an object, so new properties e.g. dragging can be set.  Initially set the dragging property of each element to false 

  els[el].onmousedown=function() {this.dragging=true;} 
  els[el].onmouseup=function() {this.dragging=false;} 

  } 
 } 


 document.onmousemove = function(e) 
 { 

  for(el in els) 
  { 

   if (els[el].dragging==true) 
  { 
   els[el].style.left = e.clientX - els[el].offsetWidth/2 +'px'; 
   els[el].style.top = e.clientY - els[el].offsetHeight/2+'px'; 
  } 

 } 
 } 

</script> 
<title>Simple Drag</title> 
</head> 

<body> 
<div class="dragger"> Some text to drag </div> 
<br><br><br><br><br><br> 
<div class="dragger"> Some other text to drag </div> 
<br><br><br><br><br><br> 
<div class="dragger"> <img src="http://www.mpklein.co.uk/images/phoenix.jpg"></img> </div> 
</body> 
</html>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.