Omnimaga

General Discussion => Technology and Development => Web Programming and Design => Topic started by: Joshuasm32 on May 21, 2014, 09:08:14 pm

Title: jQuery to JS conversion
Post by: Joshuasm32 on May 21, 2014, 09:08:14 pm
I hate jQuery, and I also am quite a noob at it (although I am great at normal JS).  Every now and then, I encounter a good snippet that happens to use jQuery in it...  Can someone here help me to convert it into pure JS to use?

My most recent issue:
Code: [Select]

var txt = $('#comments'),
    hiddenDiv = $(document.createElement('div')),
    content = null;


hiddenDiv.addClass('hiddendiv common');


$('body').append(hiddenDiv);


txt.on('keyup', function () {


    content = $(this).val();


    content = content.replace(/\n/g, '<br>');
    hiddenDiv.html(content + '<br class="lbr">');


    $(this).css('height', hiddenDiv.height());


});


Thanks in advance!
Title: Re: jQuery to JS conversion
Post by: Sorunome on May 22, 2014, 09:52:45 am
but jQuery is awesome! D:
OmnomIRC uses jQuery :P
Anyways, (untested):
Code: [Select]
var txt = document.getElementById('comments'),
hiddenDiv = document.createElement('div'),
content = null,
body = document.getElementsByTadName('body')[0];


hiddenDiv.className = 'hiddendiv common';


body.appendChild(hiddenDiv);

txt.addEventListener('keyup',function(){
content = this.value;
content = content.replace(/\n/g, '<br>');
hiddenDiv.innerHTML = content + '<br class="lbr">';
this.style.height = hiddenDiv.clientHeight;
},false);
Title: Re: jQuery to JS conversion
Post by: Eeems on May 22, 2014, 10:16:58 am
Really tempting not to fix that snippet of jQuery as well.
Code: [Select]
var div = $('div').addClass('hiddendiv common');
$('body').append(div);
$('#comments').on('keyup', function () {
   div.html(
      $(this).val().replace(/\n/g,'<br/>')
   ).append(
      $('br').addClass('lbr')
   );
   $(this).css('height', div.height());
});
Optimized for memory usage. Should be a tad faster as well with less variable declarations.

In plain JavaScript it would look like this:
Code: [Select]
var div = document.createElement('div');
   div.className = 'hiddendiv common';
document.getElementById('comments').onkeyup = function () {
   div.innerHTML = this.value.replace(/\n/g,'<br/>') + '<br class="lbr"/>';
   this.style.height = div.offsetHeight+'px';
};
document.body.appendChild(div);