keep resizing element while mouse button is down

Viewed 89

how to keep resizing an element continiously while mouse button is down?
I tried with mousedown - without success.

$('button').on('mousedown', function(){
let targ = $('.targ');
let x = targ.height();
x++;
targ.height(x);
});
.targ{background:orange;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>PRESS</button>
<br><br>
<div class='targ'>LOREM</div>

2 Answers

you can add an setInterval() to your mousedown event, and clear it on mouseup

here are an working example of setting it to 50 milliseconds:

    var interval;
$('button').on({
  mousedown: function() {
    interval = setInterval(function() {
      let targ = $('.targ');
      let x = targ.height();
      x++;
      targ.height(x);
    }, 50);

  },
  mouseup: function() {
    window.clearInterval(interval);
  }
});

Working fiddle also here: https://jsfiddle.net/qytd5h1n/2/

hope it helps :)

You could keep track of 3 events, 'enabling' the resize function when the mouse is clicked (click), and disabling the resize function with mouseup or mouseleave. Use setInterval to both check whether the mouse click was released or moved out of the element, assigning it (the timeout) to a variable so you can abort it on both of the other events (mouseup and mouseleave)

Related