Reputation: 1839
so I have been working on a plugin for the last couple of days. The plugin is simple, get the word count inside of a textarea. That's it. Now here's the problems I've been having:
I have tried just about everything, so I took a break from it, came back to it, and once again I give up, haha! I will post the code below and a link to the fiddle as well that I have been work with.
!function($){
var TextareaWordCount = function(element, options){
this.$element = element;
this.options = options;
this.defaults = {
limit : 100
};
}
TextareaWordCount.prototype = {
constructor : TextareaWordCount,
init : function(){
var that = this,
obj = this.$element,
wordcount;
this.options = $.extend(this.defaults, this.options);
this.detectPaste();
},
getWordCount : function(words){
var words_array = words.split(/\S+/g);
console.log(words_array);
return words_array.length;
},
trimParagraph : function(){
var element = this.$element;
var options = this.options; //get the global options
var words = $(element).text().split(/\S+/);
words = words.splice(0, options.limit);
var content = words.join(" ");
$(element).val(content);
},
detectPaste : function(){
var that = this;
var element = this.$element;
$(element).bind({
paste : function(){
var words;
function first(){
return new Promise(function(resolve, reject) {
setTimeout(function(){
words = element.val();
resolve("pasted");
}, 100);
});
}
first().then(function(){
console.log(words);
var count = that.getWordCount(words);
if(count > that.options.limit){
// that.trimParagraph(element);
}
});
}
});
},
'onKeyPress' : function(){
}
};
$.fn.textareaWordCount = function(){
var _data = null;
if(arguments.length){
_data = arguments[0];
}
var _TextareaWordCount = new TextareaWordCount(this, _data);
_TextareaWordCount.init();
return this;
};
$.fn.textareaWordCount.Constructor = TextareaWordCount;
}( window.jQuery );
http://jsfiddle.net/ouhey3vd/118/
Upvotes: 0
Views: 679
Reputation: 1289
I think you are going on a really really wrong path. Instead of doing all that crazy over-complicated stuff, why don't you use the native textarea element events ?
I know the following code is very different to yours, but for the sake of simplicity, this is a very easy way to implement a word count.
var textArea = $('#text');
var textAreaInfo = $('#textInfo');
function countWords(){
textAreaInfo.html(textArea.val().split(/\S+/g).length-1);
}
textArea.keyup(function(){
countWords();
});
This won't listen for mouse events, but it's so easy to add.
Note: Using a timeout to wait for the paste event is actually a really bad idea. This is heavily under-optimized, & the timeout you are talking about may significantly vary depending on the computer's specs. Sometimes 100ms won't be enough, especially when the pasted text is huge.
Upvotes: 2