I'm trying to create a word count (for any page) bookmarklet without loading an external file. In short I want to click the bookmarklet and then be able to drag and select text on the screen and get an alert with the number of words selected. I have put this together to get the correct functionality but am stumbling on converting to bookmarklet:
<html>
<body onmouseup="countWords()">
<article id="page1">
<h1>Home 2</h1>
<p>Welcome 2</p>
<script type="text/javascript">
function countWords() {
var selectedText = document.activeElement;
var selection = selectedText.value.substring(selectedText.selectionStart, selectedText.selectionEnd);
words = selection.match(/[^\s]+/g).length;
if (words !== "") {
alert(words);
}
}
</script>
<div><textarea></textarea></div>
</article>
</body>
</html>
First issue: I may be barking up the wrong tree but I wanted to attach the onmouseup to the activeElement but am at a loss as to how to do this.
Second issue: Can I insert this in a bookmarklet without the use of an external file?
Any assistance would be greatly appreciated.
Best,
Tamler
Escape characters... That was the issue.
Here is a working example:
<a href="javascript:(document.onmouseup=function(){var selectedText=document.activeElement;var selection=selectedText.value.substring(selectedText.selectionStart,selectedText.selectionEnd);words=selection.match(/[^\s]+/g).length;if(words!==""){alert(words)}})();" target="_blank">Word Count</a>