Ahmed Mohsen
Ahmed Mohsen

Reputation: 433

Why OnMouseDown Event occur once , how to handle mouse hold event

the difference between mouse click and mouse down - that mouse click occurs only once , but mouse down occurs every tick my mouse is down

here's in my simple example - I don't know why the event occur only once , however I am using mouse down not mouse click

<canvas id="drawhere" onmousedown="console.log('HH')" width="600" height="500"></canvas>

It writes 'HH' only once !! mouse up and down again - to write it again

I need it to be written every tick as my mouse is down - any help :))

I don't use jquery , javascript only

Upvotes: 0

Views: 5655

Answers (2)

Scott Marcus
Scott Marcus

Reputation: 65815

mouseup and mousedown are not supposed to continuously fire. They are meant to signal a single action has happened.

However, you could achieve this effect with a custom timer (setInterval() to be more specific) that is triggered on mousedown and cancelled on mouseup:

document.getElementById("main");

var timer = null;  // Variable to hold a reference to the timer

// Set up an event handler for mousedown
main.addEventListener("mousedown", function(evt){
  // Start a timer that fires a function at 50 millisecond intervals
  timer = setInterval(function(){
    // the function can do whatever you need it to
    console.log("Mouse is down!");
  }, 50);
});

// Set up a custom mouseup event handler for letting go 
// of the mouse inside the box or when mouse leaves the box.
function mouseDone(evt){
  clearInterval(timer);         // Cancel the previously initiated timer function
  console.log("Mouse is up or outside of box!");  // And, do whatever else you need to
}

// Bind the handlers:
main.addEventListener("mouseup", mouseDone);
main.addEventListener("mouseleave", mouseDone);
#main {
  background-color:yellow;
  width: 300px;
  height: 100px;
}
<div id="main">Press and hold the mouse down inside me!</div>

Upvotes: 5

Parzibyte
Parzibyte

Reputation: 1598

Use "onmousemove" instead "onmouseover" and I recommend you use a function like this in your javascript code:

document.getElementById("drawhere").addEventListener("mousemove", function(){
    console.log("mouse event!");
});

Working pen: http://codepen.io/parzibyte/full/ENzjvW/

Upvotes: 0

Related Questions