mots/js/jquery.explanationCheck.js
2019-09-02 16:37:11 +02:00

72 lines
2.3 KiB
JavaScript

(function ($) {
$.fn.explanationCheck = function (terms, options) {
return this.each(function () {
$.checkText(this, terms, options);
});
};
$.fn.explanationCheck.defaults = {
details: $('#details'),
counter: $('#counter'),
wordList: $('#wordList'),
separator: '<br/>',
ignoredCharacters: '\.\!,;\?',
splitCharacters:""
};
$.createCheckWorld = function(options, a) {
options.counter = typeof options.counter == 'string' ? options.counter[0] == '#' ? $(options.counter) : $("#"+options.counter) : options.counter;
options.wordList = typeof options.wordList == 'string' ? options.wordList[0] == '#' ? $(options.wordList) : $("#"+options.wordList) : options.wordList;
options.details = typeof options.details == 'string' ? options.details[0] == '#' ? $(options.details) : $("#"+options.details) : options.details;
if(options.counter.length == 0) options.counter = $('<span id="counter">0</span>').insertAfter(a);
if(options.wordList.length == 0) options.wordList = $('<span id="wordList"></span>').insertAfter(a);
}
$.updateWrongWord = function(o,w,c){
o.counter.html(c);
o.wordList.html(w.join(o.separator));
}
$.checkText = function (area, terms, options) {
options = $.extend({}, $.fn.explanationCheck.defaults, options);
var $area = $(area),
words = "",
counter = 0,
wrongWords = []
$countEl = typeof options.counter == 'string' ? $(options.counter) : options.counter;
$area.terms = terms;
$area.options = options;
$.createCheckWorld(options, $area);
$area.keyup(function(e){
if($(this).getSelection.length == 0){
counter = 0;
wrongWords = [];
words = $area.val().replace(new RegExp("["+$area.options.ignoredCharacters+"]","g"), '');
words = words.split(/[\s\n']+/g);
for(var i = 0, l = words.length; i < l ; i++){
var w = $.trim(words[i]).toLowerCase();
if(w != '' && !~terms.indexOf(w)){
wrongWords.push(w);
counter = wrongWords.length;
}
}
$.updateWrongWord(options, wrongWords, counter);
$countEl.updateCounter(counter);
}
});
$countEl.updateCounter = function(){
if(counter == 0){
$area.options.details.css('visibility','hidden');
}else{
$area.options.details.css('visibility','visible');
}
$countEl.html(counter);
}
return $area;
};
}(jQuery));