Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firefox drags div like it was an image

I'm using this HTML,CSS and Javascript code (in one document together if you want to test it out):

<style type="text/css">
#slider_container {
    width: 200px;
    height: 30px;
    background-color: red;
    display:block;
}

#slider {
    width: 20px;
    height: 30px;
    background-color: blue;
    display:block;
    position:absolute;
    left:0;
}
</style>
<script type="text/javascript" src="../../js/libs/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {

   $("#slider").mousedown(function() {
       $(document).mousemove(function(evnt) {
       $("#test").html("sliding");
   }).mouseup(function() {
       $("#test").html("not sliding");
       $(document).unbind("mousemove mouseup");
   });});

});
</script>

<div id="test">a</div>
<div id="slider_container">
  <div id="slider"></div>
</div>

Everything (surprisingly) works fine in IE, but firefox seems to totally clusterf*ck when this javascript is used. The first "slide" is okay, you drag, it says "sliding", you drop, it says "not sliding". On the second "slide" (or mousedown if you will), firefox suddenly thinks the div is an image or link and wants to drag it around.

Screenshot of the dragging:

http://i.imgur.com/nPJxZ.jpg

Obviously the blue div half-positioned in the red div is the one being dragged. Windows does not capture the cursor when you take a screenshot, but it's a stop sign.

Is there someway to prevent this default behaviour?

like image 852
soren.qvist Avatar asked Mar 12 '10 01:03

soren.qvist


1 Answers

You need to return false from the event handlers to prevent the default action (selecting text, dragging selection, etc). Based on the code posted by Crispy, Here is my solution:

$(function() {
    var sliderMouseDown = false;

    $("#slider").mousedown(function() {
        sliderMouseDown = true;
        return false;
    });
    $(document).mousemove(function(evnt) {
        if (sliderMouseDown) {
            $("#test").html("sliding");
            return false;
        }
    });
    $(document).mouseup(function() {
        if (sliderMouseDown){
            $("#test").html("not sliding");
            sliderMouseDown = false;
            return false;
        }
    });
});
like image 132
Marius Avatar answered Sep 29 '22 11:09

Marius