0

I have a large number of DIVs aligned like this:

+---------------+
| DIV 1         |
+---------------+
| DIV 2         |
+---------------+
| DIV 3         |
+---------------+
| ...           |

I want to change to toggle the class of each DIV when the user holds the left mouse button and hovers over them.

isMouseDown = false

$('body').mousedown(function () {
    isMouseDown = true;
})
.mouseup(function () {
    isMouseDown = false;
});

$(".div").live("mouseenter", function () {

    if (isMouseDown) {
        $(this).toggleClass("selected");
    }
});

I currently do it this way, but it only really works when the user is using the right mouse button, because the left button triggers the browser's default select behavior.

Is it possible to make this work with the left mouse as well?

EDIT: Working code:

isMouseDown = false

$('body').mousedown(function (e) {
    e.preventDefault(); // Prevent default behavior
    isMouseDown = true;
})
.mouseup(function (e) {
    e.preventDefault(); // Prevent default behavior
    isMouseDown = false;
});

$(".div").live("mouseenter", function (e) {
    e.preventDefault(); // Prevent default behavior
    if (isMouseDown) {
        $(this).toggleClass("selected");
    }
});
// Because IE8 won't get it without this...
$(".div").mousemove(function (e) {
    if ($.browser.msie) {
        e.preventDefault();
        return false;
    }
});
xsl
  • 17,116
  • 18
  • 71
  • 112

2 Answers2

2

You basically want to prevent the browser events default behavior.

Then simply use jQuerypreventDefault method.

isMouseDown = false

$('body').mousedown(function (e) {
    e.preventDefault(); // Prevent default behavior
    isMouseDown = true;
})
.mouseup(function (e) {
    e.preventDefault(); // Prevent default behavior
    isMouseDown = false;
});

$(".div").live("mouseenter", function (e) {
    e.preventDefault(); // Prevent default behavior
    if (isMouseDown) {
        $(this).toggleClass("selected");
    }
});
Arnaud Leymet
  • 5,995
  • 4
  • 35
  • 51
1

You could try preventing the default behavior of the browser click. jQuery disable a link

Community
  • 1
  • 1
avanderw
  • 675
  • 1
  • 7
  • 22