Resize for elements and not browser window

1

Help me with a quick question.

The jquery resize identifies when the browser window changes and triggers an event. So good.

But is there any way for me to know when an element changes? When to resize it?

In this case, resize does not help me. Any help?

    
asked by anonymous 12.01.2018 / 20:50

1 answer

3

You can use the code below that will listen for any change in textarea and run the code you want where I commented // faz alguma coisa aqui :

  

I include window resize if textarea is responsive. If it is of fixed width, do not need. Just change this line $(window, "textarea").on("input resize", function(){ to ta_el.on("input", function(){ .

var ta_el = $("textarea");
var ta_width = ta_el.width();
var ta_height = ta_el.height();
$(window, "textarea").on("input resize", function(){
   if(ta_el.height() != ta_height || ta_el.width() != ta_width){
      ta_width = ta_el.width();
      ta_height = ta_el.height();
      console.log("tamanho do textarea alterado"); // apenas para visualizar, pode apagar esta linha
      // faz alguma coisa aqui
   }
});

An example:

// função apenas para exemplificar. NÃO COPIE
function auto_grow(element) {
    element.style.height = "5px";
    element.style.height = (element.scrollHeight)+"px";
}

var ta_el = $("textarea");
    var ta_width = ta_el.width();
    var ta_height = ta_el.height();
    $(window, "textarea").on("input resize", function(){
       if(ta_el.height() != ta_height || ta_el.width() != ta_width){
          ta_width = ta_el.width();
          ta_height = ta_el.height();
          console.log("tamanho do textarea alterado"); // apenas para visualizar, pode apagar esta linha
          // faz alguma coisa aqui
       }
    });
textarea {
    resize: none;
    width: 100%;
    min-height: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><textareaoninput="auto_grow(this)"></textarea>
    
12.01.2018 / 21:54