How to get a JS event once the page loads?

I have code that displays the number of characters left to type.

This is my code:

<input type="text" name="title" value="" title="This is a required field." placeholder="title" maxlength="64" id="max_length_red" required>
<div class="max_length_red"></div>
<script>
(function(){
     document.addEventListener("keyup", function(event){
     if(event.target.matches("#max_length_red")){
     // get input value and length
     const value = event.target.value;
     const valueLength = event.target.value.length;
     // get data value
     const maxChars = parseInt(event.target.getAttribute("maxlength"));
     const remainingChars = maxChars - valueLength;
     if(valueLength > maxChars){
     // limit chars to maxChars
     event.target.value = value.substr(0, maxChars);
     return; //end function execution
     }
     event.target.nextElementSibling.innerHTML = remainingChars + " remainingChars";
     }
     })
})();
</script>

I am trying to change the code that will appear as soon as the page is loaded, because currently as long as I have not started writing text in the input the number of characters does not appear.

>Solution :

You can make use of the DOMContentLoaded event which is fired as soon as the page is fully loaded and rendered.

From the MDN:

window.addEventListener('DOMContentLoaded', (event) => {
    console.log('DOM fully loaded and parsed');
});

A very simple solution could be:

<input type="text" name="title" value="Some value" title="This is a required field." placeholder="title" maxlength="64" id="max_length_red" required>
<div class="max_length_red"></div>
<script>

function calculateChars(element) {
// get input value and length
   const value = element.value;
   const valueLength = element.value.length;
   // get data value
   const maxChars = parseInt(element.getAttribute('maxlength'));
   const remainingChars = maxChars - valueLength;
   if(valueLength > maxChars){
     // limit chars to maxChars
     element.value = value.substr(0, maxChars);
     return; //end function execution
   }
   element.nextElementSibling.innerHTML = remainingChars + " remainingChars";
}
(function(){
     document.addEventListener("keyup", function(event){
       if(event.target.matches("#max_length_red")){
         calculateChars(event.target);
       }
     });
     
     // Here initialize the text with maximum chars allowed
     window.addEventListener('DOMContentLoaded', function () {
      const input = document.getElementById('max_length_red');
      calculateChars(input);
     });
})();
</script>

Leave a Reply