Can't Get Variable to Add Properly - javascript

I have a variable++; in an if/else statement (it being in the else part). It's supposed to add 1 to a score of how many wrong guesses one has.
For some reason it never adds just one, it will also add numbers ranging from 3 to 7 whenever I submit a 'guess'. Can you guys tell me if I'm looping wrong or something? Please try to explain in detail.
EDIT: I realized part of the problem. The tries++; is actually looping once for each letter [var]choice didn't match or equal. For instance if I enter "a" for "apple" tries++; will loop four times because of the four other characters. So how do I get it to only loop only once instead of adding one for each missed character?
This is my code.
// JavaScript Document
var words = new Array("apple","orange","banana","lime","mango","lemon","avacado","pineapple","kiwi","plum","watermelon","peach");
var randomNum;
var word;
var tries = 0;
$('#guess').prop('disabled', true);
$(function(){
$('#start').click(function(){
$('#guess').prop('disabled', false);
word = "";
randomNum = Math.floor(Math.random() * words.length)
for (var i =0; i < words[randomNum].length; i++) {
word += "*";
}
console.log(words[randomNum]);
$('#word').html(word);
});
$('#guess').click(function guess(){
var choice = $('#letter').val().toLowerCase();
for (var i =0; i < word.length; i++) {
if (words[randomNum].charAt(i) == choice) {
word = word.substr(0, i) + choice + word.substr(i + 1);
}
if (words[randomNum].charAt(i) !== choice) {
tries++;
}
}
if (tries < 7) {
$('#tries').html(tries)
} else if (tries >= 7)
$('#tries').html("YOU LOSE");
$('#word').html(word);
$('#' + choice).css("background-color", "red");
});
});

Got it working!
The issue is related to the tries variable, inside the for loop (per letter). In order to see the odd behavior add a console.log(tries); in your code, inside the loop and you will see. At first time it will increase in 1 then the value will change completely (I will suggest some debugging here to understand what's going on with more accuracy since I did this real quick). The solution is increasing the variable out of the for loop context to make it work (I did this in the provided example from the bottom).
By the way, it seems that you are trying to implement a "Hangman" game and to be honest, when implementing those things you need to be really organized.
I fixed your issue, improved the code a lot and also considered other possible game scenarios like:
Play Again
Game Over
Win
Go Back
Please take a look. Just to know, HTML and CSS are just improvisations made for this example, some improvements are needed so just take them as a reference.
Update: What you had put in the EDIT part from your post is correct.
You can run this script at the bottom.
// Game variables
var GAME_WORDS = [ // List of words available when playing
'apple',
'orange',
'banana',
'lime',
'mango',
'lemon',
'avacado',
'pineapple',
'kiwi',
'plum',
'watermelon',
'peach'
],
GAME_MASKED_WORD = '', // Stores the masked word to be discovered
GAME_SELECTED_WORD = '', // Stores the readable word
GAME_PLAYER_ATTEMPTS = 0, // Stores player attempts when failing
GAME_RANDOM_NUMBER = 0, // Random number to pick a word
GAME_MAX_ATTEMPTS = 7, // Max. player attempts before a game over
GAME_UI_COMPONENTS = { // UI components declaration
start: $('#start'),
reset: $('#reset'),
back: $('#back'),
guess: $('#guess'),
msg: $('#msg'),
word: $('#word'),
letter: $('#letter')
},
GAME_UI_SECTIONS = { // UI sections declaration
menu: $('#menu'),
game: $('#game')
};
$(function() {;
var ui = GAME_UI_COMPONENTS;
// Initialize game
init();
// Start button handler
ui.start.on('click', function(e) {
start();
});
// Guess button handler
ui.guess.on('click', function(e) {
guess();
});
// Play Again button handler
ui.reset.on('click', function(e) {
reset();
start();
});
// Go Back button handler
ui.back.on('click', function(e) {
init();
});
});
/**
* Used to initialize the game for first time
*/
function init() {
var sections = GAME_UI_SECTIONS;
sections.menu.show();
sections.game.hide();
reset();
};
/**
* Used to start the game
*/
function start() {
var ui = GAME_UI_COMPONENTS,
sections = GAME_UI_SECTIONS,
words = GAME_WORDS;
sections.menu.hide();
sections.game.show();
GAME_RANDOM_NUMBER = Math.floor(Math.random() * words.length);
for (var i = 0; i < words[GAME_RANDOM_NUMBER].length; ++i) {
GAME_MASKED_WORD += '*';
}
GAME_SELECTED_WORD = words[GAME_RANDOM_NUMBER];
ui.word.html(GAME_MASKED_WORD);
ui.letter.focus();
};
/**
* Guess button handler
*/
function guess() {
var ui = GAME_UI_COMPONENTS,
words = GAME_WORDS,
matches = false,
choice;
// Clean messages each time player do a guess
showMsg('');
if (ui.letter && ui.letter.val()) {
choice = $.trim(ui.letter.val().toLowerCase());
}
if (choice) {
for (var i = 0; i < GAME_MASKED_WORD.length; ++i) {
if (words[GAME_RANDOM_NUMBER].charAt(i) === choice) {
GAME_MASKED_WORD = GAME_MASKED_WORD.substr(0, i) + choice +
GAME_MASKED_WORD.substr(i + 1);
matches = true;
}
}
if (!matches) {
++GAME_PLAYER_ATTEMPTS;
}
} else {
showMsg('Please type a letter.');
}
// Show attempts left if more than zero
if (GAME_PLAYER_ATTEMPTS > 0) {
showMsg('You have ' +
(GAME_MAX_ATTEMPTS - GAME_PLAYER_ATTEMPTS) +
' attempt(s) left.');
}
// Check game status each time doing a guess
if (isGameOver()) {
lose();
} else if (isGameWin()) {
win();
} else {
ui.word.html(GAME_MASKED_WORD);
}
ui.letter.focus();
};
/**
* Used to set all game variables from the scratch
*/
function reset() {
var ui = GAME_UI_COMPONENTS;
GAME_MASKED_WORD = '';
GAME_PLAYER_ATTEMPTS = 0;
GAME_RANDOM_NUMBER = 0;
showMsg('');
ui.guess.show();
ui.letter.val('');
ui.word.html('');
};
/**
* Handler when player lose the game
*/
function lose() {
var ui = GAME_UI_COMPONENTS;
showMsg('You Lose!');
ui.word.html(GAME_SELECTED_WORD);
ui.guess.hide();
};
/**
* Handler when player win the game
*/
function win() {
var ui = GAME_UI_COMPONENTS;
showMsg('You Win!');
ui.word.html(GAME_SELECTED_WORD);
ui.guess.hide();
};
/**
* Use to print UI messages for the player
*/
function showMsg(msg) {
var ui = GAME_UI_COMPONENTS;
ui.msg.html(msg);
};
/**
* Check game status, if player is going to lose the game
* #returns Boolean
*/
function isGameOver() {
return (GAME_PLAYER_ATTEMPTS >= GAME_MAX_ATTEMPTS);
};
/**
* Check game status, if player is going to win the game
* #returns Boolean
*/
function isGameWin() {
return (GAME_MASKED_WORD === GAME_SELECTED_WORD);
};
.btn {
cursor: pointer;
}
span#msg {
color: red;
font-weight: bold;
}
.text {
font-size: 3em;
}
input#letter {
width: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="wrapper">
<div id="menu">
<span class="text">Hangman!</span>
<br><br>
<img src="http://img3.wikia.nocookie.net/__cb20130207191137/scribblenauts/images/0/01/Hangman.png" height="200" width="120"/>
<br><br>
<input type="button" class="btn" id="start" value="Start Game"/>
</div>
<div id="game">
<span id="msg"></span>
<br><br>
Letter: <input type="text" id="letter" value="" maxlength="1"/>
<br><br>
<input type="button" class="btn" id="guess" value="Guess"/>
<input type="button" class="btn" id="reset" value="Play Again"/>
<input type="button" class="btn" id="back" value="Go Back"/>
<br><br>
Word: <div id="word" class="text"></div>
</div>
</div>
Hope this helps.

try this one:
Modify guess click handler like this:
$('#guess').click(function guess(){
var choice = $('#letter').val().toLowerCase(),
found = false;
for (var i =0; i < word.length; i++) {
if (words[randomNum].charAt(i) == choice) {
word = word.substr(0, i) + choice + word.substr(i + 1);
found = true
}
}
if(!found){
tries++;
}
if (tries < 7) {
$('#tries').html(tries)
} else if (tries >= 7){
$('#tries').html("YOU LOSE");
}
$('#word').html(word);
$('#' + choice).css("background-color", "red");
});
Also on start reset the tries:
$('#start').click(function(){
$('#guess').prop('disabled', false);
word = ""; tries = 0;

Related

How do you wait for a button to get pressed a certain amount of times before running another function?

I am trying to build a gambling simulator that lets you gamble with fake money to see if you'd win more often times than not. The game I am sort of trying to replicate is Mines from Roobet. In my game, there are 9 squares laid out in a grid like format. One of the squares is the bomb square, which means if you click it, you lose. The player does not know which square is the bomb square though. You have to click 4 squares, and if all of the ones you have clicked are non-bomb squares, then you win $50. If you click the bomb square, then you lose $50.
What I have been trying to figure out for like a week now is how do you make the game wait until either 4 non-bomb squares have been clicked, or 1 bomb square to have been clicked in order to do certain functions(subtract 50 from gambling amount, restart the game). I have tried while loops, but that crashes the browser. I have also tried if-else statements, but the code doesn't wait until either 4 non-bomb squares or 1 bomb square has been clicked. It just checks it instantly. So it results in it not working right. I also have tried for the function to call itself, and then check for either case, but it just results in an error saying "Maximum call stack size exceeded."
function bombClicked () {
for (let i = 0; i < array.length; i++) { //each square is put into an array named array
array[i].addEventListener("click", () => {
if (array[i].value == "bomb") {
array[i].style.background = "red";
redCounter++;
didLose = true
}
else{
array[i].style.background = "green";
greenCounter++;
didLose = false;
}
})
}
if (greenCounter >= 4 || redCounter >= 1) {
if (didLose == true) {
gamblingAmount.value = parseInt(gamblingAmount.value) - 50;
}
else {
gamblingAmount.value = parseInt(gamblingAmount.value) + 50;
}
reset();
}
}
What a fun little exercise! Here's my quick and dirty jquery solution.
const NO_OF_TRIES_ALLOWED = 4;
const SCORE_WON_LOST = 50;
var score = 0;
var tries = 0;
var bombId;
function restart() {
tries = 0;
$("button").removeClass("ok");
$("button").removeClass("bang");
bombId = Math.floor( Math.random() * 9);
$("#bombLabel").text(bombId);
}
function win() {
window.alert('you win!');
score += SCORE_WON_LOST;
$("#scoreLabel").text(score);
restart();
}
function lose(){
window.alert('you lose!');
score -= SCORE_WON_LOST;
$("#scoreLabel").text(score);
restart();
}
$(document).on("click", "button", function() {
if( !$(this).is(".bang") && !$(this).is(".ok") ) {
let buttonId = $(this).data("id");
if(buttonId === bombId) {
$(this).addClass('bang');
setTimeout(lose, 100); // bit of a delay before the alert
}
else {
$(this).addClass('ok');
tries++;
if(tries === NO_OF_TRIES_ALLOWED) {
setTimeout(win, 100); // bit of a delay before the alert
}
}
}
});
restart();
button{
width: 50px;
height: 50px;
padding: 0;
}
.ok{
background-color: green;
}
.bang{
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button data-id="0"></button>
<button data-id="1"></button>
<button data-id="2"></button><br>
<button data-id="3"></button>
<button data-id="4"></button>
<button data-id="5"></button><br>
<button data-id="6"></button>
<button data-id="7"></button>
<button data-id="8"></button><br>
Score: <span id="scoreLabel"></span>
It looks like you need some sort of state. I don't know what the rest of your code looks like, but maybe creating a helper to keep track of your counts might help:
class Counter {
constructor() {
this.count = 0;
}
inc() {
this.count ++;
}
getCount() {
return this.count
}
}
const counter = new Counter();
counter.inc();
counter.inc();
counter.inc();
counter.getCount(); // 3
Javascript should keep this in memory for you. I might have to see the rest of your code to understand how exactly to fix the issue, but maybe this will put you on the right track!

Rock Paper Scissors game loop

I'm working on a task to build a Stone,Paper,Scissors Game.
The game is supposed to run in 3 possible modes. best of 3 / best of 5 and endless games.
My code works fine until the point where I reset the game to begin a new game.
For a reason which I can not figure out, it plays multiple instances of my game, each time I call the game() function.
(after the game is over - a reset game button appears and the game mode needs to be reseleted)
I've added the entire project to this https://jsfiddle.net/vydkg3bz/, since I don't manage to pinpoint where the issue is.
I believe, due to all the extra logging I added, that the problem is somewhere in the game() function, as I tried to replace most of the code around it, with the same result.
Maybe someone has a moment to review my code and give me a hint where I should look?
// global variables
var choicesObj = {
Rock: "url('./img/stone.png')",
Paper: "url('./img/paper.png')",
Scissors: "url('./img/scissors.png')",
}
var choices = Object.keys(choicesObj);
var moveAI;
var movePlayer;
var winnerRound;
var winnerGame;
var roundCount = 0;
// actual game
function game(requiredWins) {
console.log("game");
enabler()
var inputs = document.querySelectorAll(".inputButton");
console.log(inputs);
for (var i = 0; i < inputs.length; i++) {
inputs[i].addEventListener("click", function() {
movePlayer = this.id
handleClick(movePlayer)
});
}
// checking choice, display choice IMG, call compareChoices function
function handleClick(buttonID) {
console.log("handleClick");
moveAIfunc()
movePlayer = buttonID;
console.log('movePlayer: ' + movePlayer);
console.log('moveAI: ' + moveAI);
document.getElementById("mainImgPlayer").style.backgroundImage = choicesObj[movePlayer];
document.getElementById("mainImgAI").style.backgroundImage = choicesObj[moveAI];
compareChoices(moveAI,movePlayer);
console.log("requiredWins", requiredWins);
gameEnd();
displays();
}
// AI control
function moveAIfunc() {
moveAI = choices[Math.floor(Math.random() * choices.length)]
}
// compare choices
function compareChoices(a, b) {
console.log("compareChoices");
a = choices.indexOf(a);
b = choices.indexOf(b);
console.log("requiredWins", requiredWins);
roundCount++;
if (a == b) {
winnerNone()
return;
}
if (a == choices.length - 1 && b == 0) {
winnerPlayer()
return;
}
if (b == choices.length - 1 && a == 0) {
winnerAI()
return;
}
if (a > b) {
winnerAI()
return;
}
else {
winnerPlayer()
return;
}
}
// game end
function gameEnd() {
console.log("gameEnd");
console.log(requiredWins,winsPlayer,winsAI);
if (winsPlayer == requiredWins) {
console.log(requiredWins,winsPlayer,winsAI);
winnerGame = "Player";
disabler()
createEndButton()
return;
}
if (winsAI == requiredWins) {
console.log(requiredWins,winsPlayer,winsAI);
winnerGame = "AI";
disabler()
createEndButton()
return;
}
}
}```
Your code seems to be pretty complicated. The state of the wins/required wins etc. is not saved adequately in it. For playing you add event listeners per game (click), which is pretty inefficient imho.
I have created a mockup (a minimal reproducable example) for the handling of games, using data attributes to remember the state of a game and event delegation for the handling. Maybe it's useful for you.
Not related, but here's my take on RPS.
document.addEventListener(`click`, handle);
function handle(evt) {
if (evt.target.id === `play`) {
return play(evt.target);
}
if (evt.target.name === `nWins`) {
return reset(evt.target);
}
}
function reset(radio) {
const value = radio === `none`
? Number.MAX_SAFE_INTEGER : +radio.value;
const bttn = document.querySelector(`#play`);
const result = document.querySelector(`#result`);
result.textContent = `(Re)start initiated, click [Play]`;
result.dataset.wins = bttn.dataset.wins = 0;
bttn.dataset.plays = 0;
return bttn.dataset.winsrequired = value;
}
function play(bttn) {
if (+bttn.dataset.winsrequired < 1) {
return document.querySelector(`#result`)
.textContent = `Select best of to start playing ...`;
}
const result = document.querySelector(`#result`);
bttn.dataset.plays = +bttn.dataset.plays + 1;
const won = Math.floor(Math.random() * 2);
const wins = +result.dataset.wins + won;
result.textContent = `${won ? `You win` : `You loose`} (plays: ${
bttn.dataset.plays}, wins ${wins})`;
result.dataset.wins = wins;
if (+bttn.dataset.plays === +bttn.dataset.winsrequired) {
result.textContent = `You won ${wins} of ${
bttn.dataset.winsrequired} games. Choose 'Best of'
to start another game`;
bttn.dataset.plays = bttn.dataset.winsrequired = 0;
result.dataset.wins = 0;
document.querySelectorAll(`[name="nWins"]`)
.forEach(r => r.checked = false);
}
}
Best of
<input type="radio" name="nWins" value="3"> 3
<input type="radio" name="nWins" value="5"> 5
<input type="radio" name="nWins" value="none"> indefinite
<button id="play" data-winsrequired="0" data-plays="0" >Play</button>
<p id="result" data-wins="0"></p>

How to fix clearInterval() not stopping the interval?

I made an interval connected to a button that only runs when you have a certain amount of money and lemonade. Then I created an if statement that makes it so that when you run out of lemonade, then the interval stops. I used clearInterval() and for some reason the interval doesn't stop, and the number of lemonade goes into the negatives. Obviously you can't have a negative amount of something!
I've looked at all of the other questions with similar problems to me, but they didn't really answer my question. They all have different variables and it was hard to find an answer pertaining to my code.
Here's my code:
let autoBtnTwo = document.getElementById("autoBtnTwo");
let lemonade = 0;
let btnTwo = document.getElementById("btnTwo")
function btnTwoCost() {
wallet.removeCash(20);
update();
document.getElementById("lemonade").innerHTML = lemonade += 30
}
function double() {
if (wallet.getCash() >= 50) {
wallet.addCash(2)
update();
document.getElementById("lemonade").innerHTML = lemonade -= 1;
}
}
function autoLemonade() {
if (wallet.getCash() >= 3000) {
wallet.removeCash(3000);
var myint = setInterval(double, 1000);
autoBtnTwo.disabled = false;
update();
}
if (wallet.getCash() <= 2999) {
autoBtnTwo.disabled = true;
}
if (lemonade <= 0) {
autoBtnTwo.disabled = true;
btnTwo.disabled = true;
}
}
function stopInterval() {
var myint = setInterval(double, 1000);
if (lemonade <= 0) {
clearInterval(myint);
stopInterval();
}
}
function thousand() {
wallet.addCash(1000)
update();
if (wallet.getCash() >= 3000) {
autoBtnTwo.disabled = false;
}
}
function Wallet() {
return {
addCash: function(val) {
number += val;
},
getCash: function() {
return number;
},
removeCash: function(val) {
number -= val;
}
}
}
var number = 0;
const wallet = new Wallet();
var SUFFIXES = 'KMBTqQsSOND';
function update() {
document.getElementById('number').textContent = getSuffixedNumber(wallet.getCash());
}
function getSuffixedNumber(num) {
var power = Math.floor(Math.log10(num));
var index = Math.floor(power / 3)
num = num / Math.pow(10, (index * 3)); // first 3 digits of the number
return num.toFixed(1) + (SUFFIXES[index - 1] || ''); // default to no suffix if it gets an out of bounds index
}
<button onclick="autoLemonade()" class="chocolate-bar-auto" id="autoBtnTwo" disabled>
Hire worker: <br> -$3000<br> Sells Lemonade
</button>
<button onclick="thousand()">to get to $3000 for testing </button>
<button onclick="btnTwoCost()"> buy lemonade -$20</button>
<button onclick="double()">sell lemonade </button>
<div class="cash-div">
Cash: <div id="number">0</div>
</div>
<div class="lemonade-div">
Lemonade: <div id="lemonade">0</div>
</div>
Sorry if this version is glitchy. All of the code I used to prevent the glitches makes the code longer, which it is already long enough. press the $3,000 button 4 times, then the buy lemonade, and then the hire worker button and you will see what happens once it gets to 0.
The interval should stop adding money, and stop reducing the amount of lemonade when lemonade reaches 0, but instead it keeps going into the negatives.

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.");
}
}

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

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

Categories