jQuery "keyup" crashing page when checking 'Word Count' - javascript

I have a word counter running on a DIV and after typing in a few words, the page crashes. The browser continues to work (par scrolling) and no errors are showing in Chrome's console. Not sure where I'm going wrong...
It all started when I passed "wordCount(q);" in "keyup". I only passed it there as it would split-out "NaN" instead of a number to countdown from.
JS:
wordCount();
$('#group_3_1').click(function(){
var spliced = 200;
wordCount(spliced);
}) ;
$('#group_3_2').click(function(){
var spliced = 600;
wordCount(spliced);
}) ;
function wordCount(q) {
var content_text = $('.message1').text(),
char_count = content_text.length;
if (char_count != 0)
var word_count = q - content_text.replace(/[^\w ]/g, "").split(/\s+/).length;
$('.word_count').html(word_count + " words remaining...");
$('.message1').keyup(function() {
wordCount(q);
});
try
{
if (new Number( word_count ) < 0) {
$(".word_count").attr("id","bad");
}
else {
$(".word_count").attr("id","good");
}
} catch (error)
{
//
}
};
HTML:
<input type="checkbox" name="entry.3.group" value="1/6" class="size1" id="group_3_1">
<input type="checkbox" name="entry.3.group" value="1/4" class="size1" id="group_3_2">
<div id="entry.8.single" class="message1" style="height: 400px; overflow-y:scroll; overflow-x:hidden;" contenteditable="true"> </div>
<span class="word_count" id="good"></span>
Thanks in advanced!

This is causing an infinite loop if (new Number(word_count) < 0) {.
Your code is a mess altogether. Just study and start with more basic concepts and start over. If you want to describe your project to me in a comment, I would be glad to show you a good, clean, readable approach.
Update:
Part of having a good architecture in your code is to keep different parts of your logic separate. No part of your code should know about or use anything that isn't directly relevant to it. Notice in my word counter that anything it does it immediately relevant to its word-counter-ness. Does a word counter care about what happens with the count? Nope. It just counts and sends the result away (wherever you tell it to, via the callback function). This isn't the only approach, but I just wanted to give you an idea of how to approach things more sensefully.
Live demo here (click).
/* what am I creating? A word counter.
* How do I want to use it?
* -Call a function, passing in an element and a callback function
* -Bind the word counter to that element
* -When the word count changes, pass the new count to the callback function
*/
window.onload = function() {
var countDiv = document.getElementById('count');
wordCounter.bind(countDiv, displayCount);
//you can pass in whatever function you want. I made one called displayCount, for example
};
var wordCounter = {
current : 0,
bind : function(elem, callback) {
this.ensureEditable(elem);
this.handleIfChanged(elem, callback);
var that = this;
elem.addEventListener('keyup', function(e) {
that.handleIfChanged(elem, callback);
});
},
handleIfChanged : function(elem, callback) {
var count = this.countWords(elem);
if (count !== this.current) {
this.current = count;
callback(count);
}
},
countWords : function(elem) {
var text = elem.textContent;
var words = text.match(/(\w+\b)/g);
return (words) ? words.length : 0;
},
ensureEditable : function(elem) {
if (
elem.getAttribute('contenteditable') !== 'true' &&
elem.nodeName !== 'TEXTAREA' &&
elem.nodeName !== 'INPUT'
) {
elem.setAttribute('contenteditable', true);
}
}
};
var display = document.getElementById('display');
function displayCount(count) {
//this function is called every time the word count changes
//do whatever you want...the word counter doesn't care.
display.textContent = 'Word count is: '+count;
}

I would do probably something like this
http://jsfiddle.net/6WW7Z/2/
var wordsLimit = 50;
$('#group_3_1').click(function () {
wordsLimit = 200;
wordCount();
});
$('#group_3_2').click(function () {
wordsLimit = 600;
wordCount();
});
$('.message1').keydown(function () {
wordCount();
});
function wordCount() {
var text = $('.message1').text(),
textLength = text.length,
wordsCount = 0,
wordsRemaining = wordsLimit;
if(textLength > 0) {
wordsCount = text.replace(/[^\w ]/g, '').split(/\s+/).length;
wordsRemaining = wordsRemaining - wordsCount;
}
$('.word_count')
.html(wordsRemaining + " words remaining...")
.attr('id', (parseInt(wordsRemaining) < 0 ? 'bad' : 'good'));
};
wordCount();
It's not perfect and complete but it may show you direction how to do this. You should use change event on checkboxes to change wordsLimit if checked/unchecked. For styling valid/invalid words remaining message use classes rather than ids.

I think you should use radio in place of checkboxes because you can limit 200 or 600 only at a time.
Try this like,
wordCount();
$('input[name="entry.3.group"]').click(function () {
wordCount();
$('.word_count').html($(this).data('val') + " words remaining...");
});
$('.message1').keyup(function () {
wordCount();
});
function wordCount() {
var q = $('input[name="entry.3.group"]:checked').data('val');
var content_text = $('.message1').text(),
char_count = content_text.length;
if (char_count != 0) var word_count = q - content_text.replace(/[^\w ]/g, "").split(/\s+/).length;
$('.word_count').html(word_count + " words remaining...");
try {
if (Number(word_count) < 0) {
$(".word_count").attr("id", "bad");
} else {
$(".word_count").attr("id", "good");
}
} catch (error) {
//
}
};
Also you can add if your span has bad id then key up should return false;
See Demo

Related

Text operations: Detect replacement from clipboard

General Info
Working on my own implementation of the operational transformation algorithm. For those that don't know what this is: When multiple users work on the same document at the same time, this algorithm attempts to preserve each users intention and make sure all users end up with the same document.
The problem
To begin, I need a proper way of detecting text operations. Like insert and delete. Obviously I need to know exactly at which position this is happening so each operation can be correctly transformed by the server to preserve the intention of other users.
My code so far is doing a pretty decent job at this. But it gets in trouble when selecting a text range and replacing it with another. I rely on the input event for this, and it seems to be unable to detect both delete and insert operations at the same time. When doing this, it detects a delete operation on the selected text. But it does not detect the insert operation of the text pasted in from the clipboard.
My question is: How can I solve this issue?
My code (so far)
let txtArea = {};
let cursorPos = {};
let clientDoc = ""; // Shadow DOC
document.addEventListener("DOMContentLoaded", function(event){
txtArea = document.getElementById("test");
clientDoc = txtArea.value;
txtArea.addEventListener("input", function(){ handleInput(); });
txtArea.addEventListener("click", function(){ handleSelect(); });
});
/* Gets cursor position / selected text range */
function handleSelect(){
cursorPos = getCursorPos(txtArea);
}
/* Check whether the operation is insert or delete */
function handleInput(){
if(txtArea.value > clientDoc){
handleOperation("insert");
} else {
handleOperation("delete");
}
}
/* Checks text difference to know exactly what happened */
function handleOperation(operation){
let lines = "";
if(operation === "insert"){
lines = getDifference(clientDoc, txtArea.value);
} else if(operation === "delete"){
lines = getDifference(txtArea.value, clientDoc);
}
const obj = {
operation: operation,
lines: lines,
position: cursorPos
};
clientDoc = txtArea.value;
console.log(obj);
}
/* Simple function to get difference between 2 strings */
function getDifference(a, b)
{
let i = 0;
let j = 0;
let result = "";
while (j < b.length)
{
if (a[i] != b[j] || i == a.length){
result += b[j];
} else {
i++;
}
j++;
}
return result;
}
/* Function to get cursor position / selection range */
function getCursorPos(input) {
if ("selectionStart" in input && document.activeElement == input) {
return {
start: input.selectionStart,
end: input.selectionEnd
};
}
else if (input.createTextRange) {
var sel = document.selection.createRange();
if (sel.parentElement() === input) {
var rng = input.createTextRange();
rng.moveToBookmark(sel.getBookmark());
for (var len = 0;
rng.compareEndPoints("EndToStart", rng) > 0;
rng.moveEnd("character", -1)) {
len++;
}
rng.setEndPoint("StartToStart", input.createTextRange());
for (var pos = { start: 0, end: len };
rng.compareEndPoints("EndToStart", rng) > 0;
rng.moveEnd("character", -1)) {
pos.start++;
pos.end++;
}
return pos;
}
}
return -1;
}
#test {
width: 600px;
height: 400px;
}
<textarea id="test">test</textarea>
Managed to solve the problem myself, though not entirely sure if it's the best solution. I've used comments within the code to explain how I solved it:
function handleOperation(operation){
let lines = "";
if(operation === "insert"){
lines = getDifference(clientDoc, txtArea.value);
} else if(operation === "delete"){
lines = getDifference(txtArea.value, clientDoc);
}
// This handles situations where text is being selected and replaced
if(operation === "delete"){
// Create temporary shadow doc with the delete operation finished
const tempDoc = clientDoc.substr(0, cursorPos.start) + clientDoc.substr(cursorPos.end);
// In case the tempDoc is different from the actual textarea value, we know for sure we missed an insert operation
if(tempDoc !== txtArea.value){
let foo = "";
if(tempDoc.length > txtArea.value.length){
foo = getDifference(txtArea.value, tempDoc);
} else {
foo = getDifference(tempDoc, txtArea.value);
}
console.log("char(s) replaced detected: "+foo);
}
} else if(operation === "insert"){
// No need for a temporary shadow doc. Insert will always add length to our shadow doc. So if anything is replaced,
// the actual textarea length will never match
if(clientDoc.length + lines.length !== txtArea.value.length){
let foo = "";
if(clientDoc.length > txtArea.value.length){
foo = getDifference(txtArea.value, clientDoc);
} else {
foo = getDifference(clientDoc, txtArea.value);
}
console.log("char(s) removed detected: "+foo);
}
}
const obj = {
operation: operation,
lines: lines,
position: cursorPos
};
// Update our shadow doc
clientDoc = txtArea.value;
// Debugging
console.log(obj);
}
I'm still very much open to better solutions / tips / advise if you can give it to me.

Animate array from user input like typewriter (javascript)

I suppose my question is a bit similar to this one, but I can't really work out how to do my specific need from it. I'm building a very basic text adventure, and I'd like the returned text - after the user has entered a command - to be returned in a typewriter style. Here's a snippet of my commands so far (there'll be a lot more, I don't mind that this will be built in a bit of a tedious way)
<script>
textIn = document.getElementById("input-textbox");
textOut = document.getElementById("output-textbox");
function process(input) {
if (input == "hi") { textOut.innerHTML += "Hello to you too!<br><br>"; }
else if (input == "exit") { textOut.innerHTML += "No."; }
}
function go() {
var input = textIn.value;
textIn.value = "";
var output = process(input);
textOut.value += output + "\n";
}
</script>
and the HTML
<div id="output-textbox">
Returned text goes here.
</div>
<form onSubmit="go();return false;">
<input id="input-textbox" name="command" value="" autofocus="autofocus"/>
</form>
Thank you so much for your help in advance! This solution doesn't need to be beautiful, code wise, nor very nifty. It just has to work, I have no standards at all with this!
Based on William B's answer, here is a more condensed version:
https://jsfiddle.net/sators/4wra3y1p/1/
HTML
<div id="output-typewriter"></div>
Javascript
function typewriterText(text) {
var outEl = document.querySelector('#output-typewriter');
var interval = 50; // ms between characters appearing
outEl.innerHTML = '';
text.split('').forEach(function(char, i){
setTimeout(function () {
outEl.innerHTML += char;
}, i * interval);
});
}
typewriterText('this is an example');
Create a timeout for each character inside a loop, with each timeout being a bit later than the last. See: https://jsfiddle.net/fswam77j/1/
var outputEl = document.querySelector('#output-textbox');
var charInterval = 50; // ms between characters appearing
function showOutput(text) {
outputEl.innerHTML = '';
for(var i = 0; i < text.length; i++) {
showChar(text, i);
}
}
function showChar(text, i) {
setTimeout(function () {
outputEl.innerHTML += text[i];
}, i * charInterval);
}
showOutput('this is an example');
process the input:
function process(input) {
if (input == "hi") {
showOutput("Hello to you too!");
}
else if (input == "exit") {
showOutput("No.");
}
}

Checking a div for duplicates before appending to the list using jQuery

This should be trivial but I'm having issues...
Basically what I am trying to do is append a new "div" to "selected-courses" when a user clicks on a "course". This should happen if and only if the current course is not already in the "selected-courses" box.
The problem I'm running into is that nothing is appended to the "selected-courses" section when this is executed. I have used alert statements to make sure the code is in fact being run. Is there something wrong with my understanding of the way .on and .each work ? can I use them this way.
Here is a fiddle http://jsfiddle.net/jq9dth4j/
$(document).on("click", "div.course", function() {
var title = $( this ).find("span").text();
var match_found = 0;
//if length 0 nothing in list, no need to check for a match
if ($(".selected-course").length > 0) {
match_found = match(title);
}
if (matched == 0) {
var out = '<div class="selected-course">' + '' + title + ''+'</div>';
$("#selected-box").append(out);
}
});
//checks to see if clicked course is already in list before adding.
function match(str) {
$(".selected-course").each(function() {
var retval = 0;
if(str == this.text()) {
//course already in selected-course section
retval = 1;
return false;
}
});
return retval;
}
There was a couple of little issues in your fiddle.
See fixed fiddle: http://jsfiddle.net/jq9dth4j/1/
function match(str) {
var retval = 0;
$(".selected-course").each(function() {
if(str == $(this).text()) {
retval = 1;
return false;
}
});
return retval;
}
You hadn't wrapped your this in a jquery object. So it threw an exception saying this had no method text().
Second your retval was declared inside the each so it wasn't available to return outside the each, wrong scope.
Lastly the if in the block:
if (matched== 0) {
var out = '';
out += '<div class="selected-course">' + '' + title + ''+'</div>';
$("#selected-box").append(out);
}
was looking at the wrong variable it was looking at matched which didn't exist causing an exception.
Relying on checking what text elements contain is not the best approach to solve this kind of question. It is prone to errors (as you have found out), it can be slow, it gives you long code and it is sensitive to small changes in the HTML. I would recommend using custom data-* attributes instead.
So you would get HTML like this:
<div class="course" data-course="Kite Flying 101">
<a href="#">
<span>Kite Flying 101</span>
</a>
</div>
Then the JS would be simple like this:
$(document).on('click', 'div.course', function() {
// Get the name of the course that was clicked from the attribute.
var title = $(this).attr('data-course');
// Create a selector that selects everything with class selected-course and the right data-course attribute.
var selector = '.selected-course[data-course="' + title + '"]';
if($(selector).length == 0) {
// If the selector didn't return anything, append the div.
// Do note that we need to add the data-course attribute here.
var out = '<div class="selected-course" data-course="' + title + '">' + title + '</div>';
$('#selected-box').append(out);
}
});
Beware of case sensitivity in course names, though!
Here is a working fiddle.
Try this code, read comment for where the changes are :
$(document).on("click", "div.course", function () {
var title = $(this).find("span").text().trim(); // use trim to remove first and end whitespace
var match_found = 0;
if ($(".selected-course").length > 0) {
match_found = match(title);
}
if (match_found == 0) { // should change into match_found
var out = '';
out += '<div class="selected-course">' + '' + title + '' + '</div>';
$("#selected-box").append(out);
}
});
function match(str) {
var retval = 0; // this variable should place in here
$(".selected-course").each(function () {
if (str == $(this).find('a').text().trim()) { // find a tag to catch values, and use $(this) instead of this
retval = 1;
return false;
}
});
return retval; // now can return variable, before will return undefined
}
Updated DEMO
Your Issues are :
1.this.text() is not valid. you have to use $(this).text().
2.you defined var retval = 0; inside each statement and trying to return it outside each statement. so move this line out of the each statement.
3.matched is not defined . it should be match_found in line if (matched == 0) {.
4. use trim() to get and set text, because text may contain leading and trailing spaces.
Your updated JS is
$(document).on("click", "div.course", function () {
var title = $(this).find("span").text();
var match_found = 0;
if ($(".selected-course").length > 0) {
match_found = match(title);
}
if (match_found == 0) {
var out = '<div class="selected-course">' + '' + title + '' + '</div>';
$("#selected-box").append(out);
}
});
function match(str) {
var retval = 0;
$(".selected-course").each(function () {
if (str.trim() == $(this).text().trim()) {
retval = 1;
return false;
}
});
return retval;
}
Updated you Fiddle

jQuery autocomplete strange behavior

I've got an issue with jQuery's autocomplete. What I am trying to do is show a suggestions list based on input. So, for instance, on input class="font" I want to have a list of font sizes and on input class="color" to have a list of color predictions.
Here is what I have:
function suggestions(input, element) {
var suggestions = [];
if (element.hasClass("color") !== -1) {
var i = 0;
while (i < 100) {
suggestions.push("color" + i.toString()); // for testing purpose
i++;
}
} else {
var nr = 1;
while (nr < 1025) {
suggestions.push(nr.toString() + "px");
nr = nr + 1;
}
}
$(element).autocomplete({
minLength: 1,
source: function (request, response) {
var counter = 0;
var filteredArray = $.map(suggestions, function (item) {
if (item.startsWith(request.term) && counter < 10) {
counter = counter + 1;
return item;
} else {
return null;
}
});
response(filteredArray);
},
autoFocus: true
});
}
The thing is, it works perfectly when I test it for inputs having any class except 'color'. When it detects a class with 'color', it will build the suggestions array accordingly but will refuse to get into the anonymous function inside autocomplete - source. Which is odd to me, 'cause the array is always constructed and the autocomplete should always be hit.
Any ideas?
Thanks!
jQuery's .hasClass() returns boolean value, so you code should look like:
if (element.hasClass("color")) { ... }
Try this JSFiddle (type symbol "c")

.each function () for cloned inputs

Trying to create the Preview form and do not understand why each function () not working in this script. Or works but only for the last cloned row and ignore the zero values ​​in the previously cloned inputs.
$('input[id^=Mult_factor_]').each(function () {
var MultFactor = $(this).val();
var TotPoints = $('#Tot_points').val();
var exp1 = "Overload";
var exp2 = "Load is: ";
if (MultFactor < 1 || TotPoints > 100) {
$('#ExemptionLimitsText').text(exp1).show();
$('#PrwTotPointsText').hide();
} else {
$('#ExemptionLimitsText').text(exp2).show();
$('#PrwTotPointsText').text($('#Tot_points').val()).show();
}
});
JSfiddle
I need: If at least one of cloned MultiFactor value is zero show "Overload"
Based on your comment, you want to display the word "Overload" if either the "Additional" field is over 100 or if any of the multifactor fields is 0.
However, your loop continues to process if either of these conditions are met.
Do not use a loop, instead search specifically for a multifaktor value of 0.
var totalPoints = parseInt($('#Tot_points').val());
if(totalPoints > 100 || $('input[name="MultFaktor"]').filter(function(){return this.value=='0'}).length > 0) {
$('#ExemptionLimitsText').text("Overload").show();
$('#PrwTotPointsText').hide();
} else {
$('#ExemptionLimitsText').text("Load is: ").show();
$('#PrwTotPointsText').text(totalPoints).show();
}
Return false on overload
var valid = true;
var exp1 = "Overload";
var exp2 = "Load is: ";
var TotPoints = $('#Tot_points').val();
$('input[name=MultFaktor]').each(function () {
var $this = $(this);
if ($.trim($(this).val()) == '0' || TotPoints > 100) {
valid = false;
} else {
$('#ExemptionLimitsText').text(exp2).show();
$('#PrwTotPointsText').text($('#Tot_points').val()).show();
}
});
if (valid == false) {
e.preventDefault();
$('#ExemptionLimitsText').text(exp1).show();
$('#PrwTotPointsText').hide();
}

Categories