I have created a jQuery script to drag elements over the document. I done the script and is working perfectly. but when I add an image the script fails. Why I cant drag an image over my document, I can drag other elements such as div, span etc . I am not interested to use jQuery UI for this purpose
my code follows
<script language="javascript" src="jquery-1.4.2.min.js"></script>
<script language="javascript">
var x1 = y1 = 0;
var drag = false;
$(document).ready(function(e){
$('#dv').mousedown(function(e){
x1 = e.pageX - parseInt($('#dv').css('left'));
y1 = e.pageY - parseInt($('#dv').css('top'));
drag = true;
})
$(document).mouseup(function(e){ drag = false; })
$(document).mousemove(function(e){
if(!drag) return
$('#dv').css('left',eval(e.pageX - x1)+'px')
$('#dv').css('top',eval(e.pageY - y1)+'px')
})
});
</script>
please check this olario.com/jquery/first.php ( a normal div with text) working perfectly
second olario.com/jquery/second.php, that doesn’t work with image
I spent two weeks to fix this issue, hope this forum will help me
Thanks a lot in advance
You can get it working with a tiny tweak in your mousedown event handler:
The preventDefault() call stops the browser from trying to natively move the image itself and lets your script take over.
Edit
To get this working in IE, you’ll also have to add a preventDefault() call to your mousemove event handler: