I am trying to convert as much jQuery into native JavaScript on a project, partially for learning more JS.
Below is some code I have that Expands a text area when Focus and on Blur makes it small again.
It works just fine except one textarea fields that are inserted into the DOM after the DOM is loaded, how can I make it work for those items as well without using jQuery?
(function() {
var descriptions = document.querySelectorAll('.edit_description');
for (var i = 0; i < descriptions.length; i++){
descriptions[i].addEventListener('blur', handler, false);
descriptions[i].addEventListener('focus', handler, false);
}
//descriptions.addEventListener('blur', handler, false);
//descriptions.addEventListener('focus', handler, false);
function handler(event) {
if (event.type === "blur") {
// It's a blur event
this.setAttribute("style","height:18px;");
this.style.height = "18px";
}
else {
// It must be a focus event
this.setAttribute("style","height:10em;");
this.style.height = "10em";
}
}
})();
This jQuery version works perfectly, even for text fields added after the DOM has already loaded and that is what I need to reproduce but in native JavaScript that does not rely on other libraries like jQuery....
$(document).on("focus", "textarea.edit_description", function() {
$(this).addClass("expanding")
$(this).animate({
height: "10em"
}, 500);
});
$(document).on("blur", "textarea.edit_description", function() {
$(this).animate({
height: "18px"
}, 500);
$(this).removeClass("expanding")
});