Search code examples
javascriptevent-handlingmouseevent

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


Solution

  • 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>