Log in

View Full Version : Count Words as they are being selected/highlighted



osirisweb
08-17-2012, 04:33 PM
Hi,

I have been searching the net for a script to accomplish the following:

Within a div container there are about 30 words per 'container' like so -->

#word1 #word2 #word3 #word4 ...and so on... (word includes the hash #)...

I am trying to find a method for when a person selects/highlights each word it counts them and displays how many words are being selected/highlighted.

Does anyone know where there is an example of this? or can anyone provide such :confused:

I have searched for days and have come up empty, therefore this post!

Many thanks in advance for your help :rolleyes:

Nile
08-17-2012, 07:26 PM
The following line of code will equal the number of array values present when the selected text is split by a space.

window.getSelection().toString().split(/\s/).length;
window.getSelection() returns a selection object which can be converted into a string containing the exact characters selected. Afterwards, you need to apply a simple split by space function (using split()) and get the length of the array returned.

https://developer.mozilla.org/en-US/docs/DOM/window.getSelection
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/split