Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

css: dragging image doesn't work in Firefox

I'm trying to move an image around when the user clicks the image and starts moving: DEMO It works in Chrome, but has strange behaviour in FF

HTML:

<div id="parent">
    <img .... >
</div>

And I handle the javascript as follows

JS:

var move = false, prevX;
$('img').on('mousedown', function(e) {
   move = true;
   prevX = e.pageX;
})
  .on('mousemove', function(e) {
      if (move === true) {
          var x = parseInt($(this).css('left')) + e.pageX - prevX;
          $(this).css('left', x);
          prevX = e.pageX;
      }
})
  .on('mouseup', function(e) {
      move = false;
});

(In my own code I do a little bit more because you are not allowed to move the image outside certain boundaries)

I don't know why, but in Firefox you can select the image and then it doesn't work anymore. Any suggestions how to fix this in FF ?

like image 660
Jeanluca Scaljeri Avatar asked Dec 12 '13 11:12

Jeanluca Scaljeri


2 Answers

You need to return false in your mousedown handler to prevent default browser behavior:

$('img').on('mousedown', function(e) {
    move = true;
    prevX = e.pageX;
    return false;
})

http://jsfiddle.net/7Lhf3/5/

like image 72
dfsq Avatar answered Nov 19 '22 05:11

dfsq


Add

$(document).on("dragstart", function() {
     return false;
});

To the top of your Javascript, this intercepts and prevents the default drag behaviour in the browser, whilst allowing you to override it later to suit your needs. The net effect being the default image ghosting you see on drag in Firefox is prevented by default.

FIDDLE

like image 2
SW4 Avatar answered Nov 19 '22 06:11

SW4