2

I'm looking for a way to run some JS when a textarea gets resized.

After an hour of searching and fiddling I have something that kinda works, but it is not good enough.

titleTextArea.mouseup(function() {
    popup.update(); titleTextArea.focus();
});

The problem with the above code is that it also runs when clicking in the textarea. The code I am running causes the textarea to get re-rendered, which should not happen while someone is working in it, as it messes with the focus.

I've tried using jQuery resizable as per this SO post. For some reason the resize event does not fire. And really I'd prefer not needing to pull in jQuery UI for this.

Is there a way to run code on textbox resize (only on completion of resize is fine) that does not get triggered by a bunch of different actions as well?

(PS: why is there no vanilla event for this?!)

Jeroen De Dauw
  • 10,321
  • 15
  • 56
  • 79
  • Did you see this answer on that SO post? https://stackoverflow.com/a/7055239/1376624 It uses mouseup too, but might be smoother – Wesley Smith Nov 22 '19 at 04:47
  • Unfortunately, resize event is consistently supported only for the whole window, or iframe. Learned that the hard way. – Andrei Kalantarian Nov 22 '19 at 04:47
  • 1
    Did you have a look at ResizeObserver API developer.mozilla.org/en-US/docs/Web/API/ResizeObserver? You can then implement a polyfill to support IE, Edge and Safari like here - https://codepen.io/florinsimion/pen/GRRLZyJ – Florin Simion Nov 22 '19 at 05:51

2 Answers2

5

A simple solution can be just adding a check for width/height, not a perfect solution though:

var ta = document.getElementById("text-area");
var width = ta.clientWidth, height = ta.clientHeight
document.getElementById("text-area").addEventListener("mouseup", function(){
  if(ta.clientWidth != width || ta.clientHeight != height){
    //do Something
    console.log('resized');
  }
  width = ta.clientWidth;
  height = ta.clientHeight;
});
<textarea id="text-area" rows="4" cols="50"></textarea>
Prawin soni
  • 423
  • 2
  • 8
  • This is so simple. Unsure how I (1) not though of this and (2) missed this solution in the other SO threads. This is the code I ended up with: https://pastebin.com/ZCP6deXG. – Jeroen De Dauw Nov 22 '19 at 08:05
0

Please try this.

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/themes/base/jquery-ui.css"
        type="text/css" media="all">
</head>
<body>
<textarea></textarea>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script type="text/javascript">
    $("textarea").resizable({
        resize: function() {
            alert("xxx");
        }
    });
</script>
</body>
</html>
Happy Son
  • 81
  • 4