I'm trying to create a simple tool to count the length of a title/meta description. I managed to create the character counter (without jQuery). However, upon page load there is a default text entered in each textarea and I would like it to be included in the count.
The length of this default text might change (people will be able to import their own title/meta description from a URL so I can't use a fixed length in the code).
Is there a way to count the content of the textarea using "document.onload"? I found various topics discussing it but since I'm a super-beginner in JS, I haven't managed to adapt the code to my own situation :-/
Thanks if you can help!
Preview on Codepen : https://codepen.io/pen/OzagNQ
Here is the HTML part:
<label for="titletag">Title</label><br>
<div class="wrap">
<textarea name="text" id="titletag" cols="100" rows="1" oninput="count_title('titletag','ctitle')">Default title (variable length).</textarea><span id="ctitle" class="counter"></span></div><br><br>
<label for="metadesc">Meta description</label><br>
<div class="wrap">
<textarea name="metadesc" cols="100" rows="5" oninput="count_mdesc()" id="metadesc">Default meta description (variable length).</textarea><span id="cmdesc" class="counter"></span></div>
And the JS part:
window.load = function() {
count_title(document.getElementById('titletag'), document.getElementById('ctitle'));
}
function count_title() {
var el_t = document.getElementById('titletag');
var length = 70;
var el_c = document.getElementById('ctitle');
el_c.innerHTML = length;
el_t.oninput = function() {
document.getElementById('ctitle').innerHTML = (length - this.value.length);
};
}
function count_mdesc() {
var el_t = document.getElementById('metadesc');
var length = 320;
var el_c = document.getElementById('cmdesc');
el_c.innerHTML = length;
el_t.oninput = function() {
document.getElementById('cmdesc').innerHTML = (length - this.value.length);
};
}
function pageRefresh() {
count_title();
count_mdesc();
}
window.onload = function() {
pageRefresh();
}