Omnimaga
General Discussion => Technology and Development => Web Programming and Design => Topic started 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:
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!
-
but jQuery is awesome! D:
OmnomIRC uses jQuery :P
Anyways, (untested):
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);
-
Really tempting not to fix that snippet of jQuery as well.
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:
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);