What mouse/touch events should I use to cause a div to change color when cursor is dragged over it?

StackOverflow https://stackoverflow.com/questions/6813087

Question

I'd like to know what mouse events I need to use for the task below.

When a cursor is dragged over a div, the div changes color.

By dragged I mean that the mouse button has been clicked once (and not released) somewhere outside the div and then the cursor has been moved over the div (the mouse button has not been released at any time during this process).

The div shouldn't respond to onmouseover. The mouse button needs to have been depressed and then dragged over the div to activate the change in the div.

I'm also wondering if there are any equivalent events for touch devices?

Was it helpful?

Solution

If i understand this right you can do the following:

  • set a global variable "mousedown" to false
  • use the "onmousedown" event to set "mousedown" to true
  • use the "onmouseover" event of your div to fire a function where you first check if mousedown is true and if so make the div visible
  • use the "onmouseup" event on your page to set "mousedown" to false again

For anything javascript related to touch event you should have a look at Sencha Touch

EDIT: If you want to avoid such frameworks. You should have a look at The HTML5 Specification. There are a couple of new events related to touch devices.

Here is a nice article about it:

http://www.html5rocks.com/en/mobile/touch.html

OTHER TIPS

I'd recommend JQueryUI for this - it has several drag-specific events built-in. The drag event for touch devices is called touchmove

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top