Reputation: 21329
Upon loading of html page function checkTweetLength
is called. This function is meant to update the number of characters typed in the textarea. But this function doesn't update the html page as it runs only once during the page load. How can I make this function dynamically update the html page ?
// JavaScript Document
window.onload = function(){
checkTweetLength();
};
function checkTweetLength() {
var tweet = document.getElementById("tweet_entered");
if(tweet.value.length > 140) {
//alert('Hey');
document.getElementById("tweet_length").innerHTML = tweet.value.length - 140;
}else {
//alert('else block');
document.getElementById("tweet_length").innerHTML = tweet.value.length;
}
}
Upvotes: 0
Views: 64
Reputation: 18566
You need to bind a keypress or change event to the text area.
Here is a working jsbin
window.onload = function(){
var tweet = document.getElementById("tweet_entered");
tweet.onkeypress = checkTweetLength;
}
function checkTweetLength() {
if(this.value.length > 140) {
console.log('Hey');
document.getElementById("tweet_length").innerHTML = 140 - this.value.length;
}else {
console.log('else block');
document.getElementById("tweet_length").innerHTML = this.value.length;
}
}
Now as soon as the user start typing in the textarea, the count will update
Hope it's useful to you
Upvotes: 0
Reputation: 2690
document.getElementById("tweet_entered").onKeyUp = checkTweetLength;
Upvotes: 1
Reputation: 21666
You can set an interval after which the function will be called. Like in below case your function will be called after 3 seconds.
setTimeout(function(){checkTweetLength()}, 3000);
Or you can call it if there is any activity (mousemove or keypress)
$(document).bind( "mousemove keypress", function () {
checkTweetLength();
});
Upvotes: 0
Reputation: 45
Just bind it to the textarea using <onchange>
. e.g. <textarea onchange=checkTweetLength(); >
(edit) or use onkeyup
to record changes as the user types...
Upvotes: 1