Search code examples
javascriptjqueryequivalent

Translating .one and .on events from JQuery to JavaScript


I found this piece of code to manage the he¡ght from textareas:

// Applied globally on all textareas with the "autoExpand" class
$(document)
    .one('focus.autoExpand', 'textarea.autoExpand', function(){
        var savedValue = this.value;
        this.value = '';
        this.baseScrollHeight = this.scrollHeight;
        this.value = savedValue;
    })
    .on('input.autoExpand', 'textarea.autoExpand', function(){
        var minRows = this.getAttribute('data-min-rows')|0, rows;
        this.rows = minRows;
        rows = Math.ceil((this.scrollHeight - this.baseScrollHeight) / 16);
        this.rows = minRows + rows;
    });

It comes from this link: https://codepen.io/vsync/pen/frudD

I would like to translate these lines to the JavaScript version.

Any help? Thanks in advance!


Solution

  • remove .autoExpand from focus.autoExpand or input.autoExpand because it's not valid event and try this.

    document.querySelectorAll('textarea.autoExpand').forEach(function(item) {
      // .one
      item.addEventListener('focus', function(e) {
        console.log('called once')
        var savedValue = this.value;
        this.value = '';
        this.baseScrollHeight = this.scrollHeight;
        this.value = savedValue;
        // remove event after called once
        item.removeEventListener(e.type, arguments.callee);
        // e.type is current event or "focus"
        // arguments.callee is current callback function
      })
      // .on
      item.addEventListener('input', function(e) {
        var minRows = this.getAttribute('data-min-rows') | 0, rows;
        this.rows = minRows;
        rows = Math.ceil((this.scrollHeight - this.baseScrollHeight) / 16);
        this.rows = minRows + rows;
      })
    })