views:

338

answers:

2

Hi,

I have a large table with with each cell being 25x25 and a div inside each one. Each div has the class of "node" and a background colour is applied to them all. I'm in the process of writing some jQuery code that will change the colour of each div when the mouse goes over it while the mouse button is down.

I currently have it so it works when I mouse over, but I only want it working when the mouse button is down aswell. I have tried many different ways to get it to work but so far I have had no look, below is my current code.

$(document).ready(function(){
  $(".node").mouseover(function(){
   $(this).css({background:"#333333"});
 });
});
+3  A: 

Try something like this:

$(document).ready(function(){

  var isDown = false;   // Tracks status of mouse button

  $(document).mousedown(function() {
    isDown = true;      // When mouse goes down, set isDown to true
  })
  .mouseup(function() {
    isDown = false;    // When mouse goes up, set isDown to false
  });

  $(".node").mouseover(function(){
    if(isDown) {        // Only change css if mouse is down
       $(this).css({background:"#333333"});
    }
  });
});

EDIT:

You may want to do a separate mousedown on .node for individual item selections.

  $('.node').mousedown(function() {
    $(this).css({background:"#333333"});
  });

EDIT:

Here's an alternative method using bind and unbind.

  $(document).mousedown(function() {
      $(".node").bind('mouseover',function(){
          $(this).css({background:"#333333"});
      });
  })
  .mouseup(function() {
    $(".node").unbind('mouseover');
  });

  $('.node').mousedown(function() {
    $(this).css({background:"#333333"});
  });
patrick dw
Thank-you Patrick! Works perfectly.
Stanni
+1 - Why there isn't a method to check for `mousedown` (and other states...we have them for `alt`, `ctrl`, etc...why not mouse?) is beyond me, even in DOM2 unless I missed something in the spec.
Nick Craver
@Stanni - As Nick Craver had noted, if the `mousedown` begins over a `.node` element, that one won't get the background. Is that suitable for you?
patrick dw
Yes, it will do fine thank-you.
Stanni
@Stanni - You're welcome. :o) I updated my answer with an additional `mosuedown` on `.node` so you can still do single item selects.
patrick dw
Ahh, good idea, I should have thought of that.
Stanni
@Stanni - OK, one more thing, then I promise I'll go away! ;o) To be thorough, I added an alternate version using `bind` and `unbind` in case you don't like variables scattered around. Done now. :o)
patrick dw
That's even better. You're right, I would prefer it without having to use the variables. Thanks again.
Stanni
A: 

Well if the mouse button goes down, changes the background, and if goes up, changes back...

$(".node").mouseup(function(){
  $(this).css({background:'#cccccc'});
}).mousedown(function(){
  $(this).css({background:'#333333'});
});

Is this what you're looking for ?

Learn more in http://api.jquery.com/mousedown/

Zuul