View Full Version : Word counting in Iframe

11-04-2012, 08:16 PM
I am making a rich text editor since 3 days.. Everything is fine except two things I want to add now. Of the things is a word count.

Well, I am using an IFrame. When the user will type, I want that simultaneously, the number of words he is typing is displayed. So here is code:

My iframe:

<iframe id="iframe"></iframe>

The paragraph to display the number of words:

<p id="num">0</p>

The function in JavaScript for the word count:

function wordcount () {
var chars = document.getElementById("iframe").contentWindow.document.body.innerHTML.length;
var regex = /\s+/gi;
var words = chars.trim().replace(regex, ' ').split(' ').length;
var answer = document.getElementById("num");
answer.innerHTML = wordcount();

Well, I want that each word the user is typing, the number of words is displyed, but it is not working.. Can someone help?

11-04-2012, 08:59 PM
Hey there,

You could make it a bit easier like this in the head section:

function cnt(w,x){
var y=w.value;
var r = 0;
a=y.replace(/\s/g,' ');
a=a.split(' ');
for (z=0; z<a.length; z++) {if (a[z].length > 0) r++;}

and this in the body section:

<form name="myform">
<textarea rows="15" name="w" cols="45"
<br />Word Count: <input type="text" name="c" value="0" size="5"
onkeyup="cnt(document.myform.w,this)" />

I tried editing yours with no luck. Try the above instead if you keep struggling.

You can see it in action here:


11-04-2012, 09:06 PM
I will try your code tomorrow..thank.. I will wait other answers as well.. By the way, instead of displaying the result in an input box, it will b better if it is in a paragraph...