Micah
Micah

Reputation: 4560

How can I calculate mouse specific movement with JavaScript

I want to know how can I calculate a mouse specific movement.

I want to have some advices how to determine the mouse is moved from A to B.

For example, like win8. When the mouse is on side of window, then drop it down, a sidebar will appear.

$(window).on('mousemove' function(e){
   if(e.pageX is on area of or close to the side of window){
      // how can I calculate if the mouse Y is from a point to a point??
      if(Y is moved from A to B){
          //do something
      }
   }
})

Upvotes: 1

Views: 733

Answers (2)

hamilton.lima
hamilton.lima

Reputation: 1920

You should have "regions" to control, and in your mousemove keep track of the last and current region, and based on the register event handlers to deal with the scenarios, for example from A to B, from C to X ,and so on. :)

here a task list :

  • create array of regions objects with x,y,width,height and name
  • in onmouse move check the current region if its different from current, then set the previous with the current and, change the current to current region name.
  • set the variable event to previous + '-' + current
  • check in your array of event handlers for any data in the event position, if there are any functions there call then

hope it helps !

Upvotes: 1

BenM
BenM

Reputation: 53208

You can determine the left hand side of the window simply by checking its width:

if(e.pageX >= ($(window).width() - 20))

Will check if the mouse is within 20px of the right-hand side of the window.

To check how far it's moved, you'll need to record the last known position somehow, and then compare it. So for example you might do something like this:

var last_pos = { x: false, y: false },
 coord_check = $(window).width() - 20; // or whatever value from the right you want to check.

$(window).on('mousemove' function(e) {

    if(e.pageX >= coord_check)
    {
        // If they're null, we can't do anything:
        if((last_pos.x !== false && last_pos.y !== false) && ((e.pageX - last_pos.x) > 20)) {
            // you can access the current position through e.pageX and e.pageY
            // last_post.x and last_pos.y will tell you the last known position
        }
    }

    // Now we need to update the last position:
    last_pos.x = e.pageX;
    last_pos.y = e.pageY;

});

Upvotes: 1

Related Questions