Javascript make event click and speech recognition work with multiple buttons - javascript

So I am using webkitSpeechRecognition and it works great, but the problem is I want to use it in multiple places at the same time and when I add it into another section on my page it doesn't work correctly.
Here is it working on its own:
var final_transcript = '';
var recognizing = false;
var ignore_onend;
var start_timestamp;
//get languages
// https://gist.githubusercontent.com/onigetoc/d5dc63320c4d08633eb7b7daf6c1ddeb/raw/e9c3da4a40db8edf4992db9219526617da811c4c/lang.json
$.get("//raw.githubusercontent.com/the-creature/language-json/master/data.json", function(data) {
var cList = $('#language');
var data = $.parseJSON(data);
$.each(data, function(i) {
var option = $('<option/>')
.attr('value', data[i].code)
.html(data[i].name)
.appendTo(cList);
});
var userLang = navigator.language || navigator.userLanguage;
$("#language").val(userLang);
});
// Speech Recognition
if (!('webkitSpeechRecognition' in window)) {
message.innerHTML = 'Web Speech API is not supported by this browser. Upgrade to Chrome version 25 or later.';
} else {
var recognition = new webkitSpeechRecognition();
recognition.continuous = true;
recognition.interimResults = true;
recognition.onstart = function() {
recognizing = true;
message.innerHTML = 'Speak now.';
talk_button.innerHTML = 'Listen';
};
recognition.onresult = function(event) {
var interim_transcript = '';
for (var i = event.resultIndex; i < event.results.length; ++i) {
if (event.results[i].isFinal) {
final_transcript += event.results[i][0].transcript;
vc_search(final_transcript);
} else {
interim_transcript += event.results[i][0].transcript;
}
}
final_span.innerHTML = final_transcript;
interim_span.innerHTML = interim_transcript;
};
recognition.onend = function() {
recognizing = false;
if (ignore_onend) {
return;
}
speechMyText(final_transcript);
if (!final_transcript) {
message.innerHTML = 'Click "Talk" and begin speaking.';
talk_button.innerHTML = 'Talk';
return;
}
};
recognition.onerror = function(event) {
if (event.error == 'no-speech') {
message.innerHTML = 'No speech was detected.';
ignore_onend = true;
}
if (event.error == 'audio-capture') {
message.innerHTML = 'No microphone was found. Ensure that a microphone is installed.';
ignore_onend = true;
}
if (event.error == 'not-allowed') {
if (event.timeStamp - start_timestamp < 100) {
message.innerHTML = 'Permission to use microphone is blocked. To change, go to chrome://settings/contentExceptions#media-stream';
} else {
message.innerHTML = 'Permission to use microphone was denied.';
}
ignore_onend = true;
}
};
}
function talkWithApp(event) {
if (recognizing) {
recognition.stop();
message.innerHTML = 'Click "Talk" and begin speaking.';
talk_button.innerHTML = 'Talk';
return;
}
final_transcript = '';
recognition.lang = language.value;
recognition.start();
ignore_onend = false;
final_span.innerHTML = '';
interim_span.innerHTML = '';
message.innerHTML = 'Click the "Allow" button above to enable your microphone.';
start_timestamp = event.timeStamp;
}
// Speech Synthesis
function speechMyText(textToSpeech) {
var u = new SpeechSynthesisUtterance();
u.text = textToSpeech;
u.lang = language.value;
u.rate = 1.0;
u.onend = function(event) {}
speechSynthesis.speak(u);
}
.message {
color:#999;
padding: 1em 0;
}
.todo, .response {
min-height:50px;
background-color: #fff;
margin-bottom: 0.5em;
padding: 1px;
color:#555;
-webkit-box-shadow: 0 0px 3px #BDBDBD;
box-shadow: 0 0px 3px #BDBDBD;
transition: all 0.3s ease-in-out;
}
<div class="container">
<div id="message" class="message">Click "Talk" and begin speaking.</div>
<div class="todo"> <span id="final_span" class="final"></span>
<span id="interim_span" class="interim"></span>
</div>
<div class="controls">
<button id="talk_button" type="button" class="btn btn-default" onclick="talkWithApp(event)">Talk</button>
<select id="language" class="select">
<option selected="selected">Select Your Language</option>
</select>
</div>
</div>
And here is it running multiple times within the same page:
var final_transcript = '';
var recognizing = false;
var ignore_onend;
var start_timestamp;
//get languages
// https://gist.githubusercontent.com/onigetoc/d5dc63320c4d08633eb7b7daf6c1ddeb/raw/e9c3da4a40db8edf4992db9219526617da811c4c/lang.json
$.get("//raw.githubusercontent.com/the-creature/language-json/master/data.json", function(data) {
var cList = $('#language');
var data = $.parseJSON(data);
$.each(data, function(i) {
var option = $('<option/>')
.attr('value', data[i].code)
.html(data[i].name)
.appendTo(cList);
});
var userLang = navigator.language || navigator.userLanguage;
$("#language").val(userLang);
});
// Speech Recognition
if (!('webkitSpeechRecognition' in window)) {
message.innerHTML = 'Web Speech API is not supported by this browser. Upgrade to Chrome version 25 or later.';
} else {
var recognition = new webkitSpeechRecognition();
recognition.continuous = true;
recognition.interimResults = true;
recognition.onstart = function() {
recognizing = true;
message.innerHTML = 'Speak now.';
talk_button.innerHTML = 'Listen';
};
recognition.onresult = function(event) {
var interim_transcript = '';
for (var i = event.resultIndex; i < event.results.length; ++i) {
if (event.results[i].isFinal) {
final_transcript += event.results[i][0].transcript;
vc_search(final_transcript);
} else {
interim_transcript += event.results[i][0].transcript;
}
}
final_span.innerHTML = final_transcript;
interim_span.innerHTML = interim_transcript;
};
recognition.onend = function() {
recognizing = false;
if (ignore_onend) {
return;
}
speechMyText(final_transcript);
if (!final_transcript) {
message.innerHTML = 'Click "Talk" and begin speaking.';
talk_button.innerHTML = 'Talk';
return;
}
};
recognition.onerror = function(event) {
if (event.error == 'no-speech') {
message.innerHTML = 'No speech was detected.';
ignore_onend = true;
}
if (event.error == 'audio-capture') {
message.innerHTML = 'No microphone was found. Ensure that a microphone is installed.';
ignore_onend = true;
}
if (event.error == 'not-allowed') {
if (event.timeStamp - start_timestamp < 100) {
message.innerHTML = 'Permission to use microphone is blocked. To change, go to chrome://settings/contentExceptions#media-stream';
} else {
message.innerHTML = 'Permission to use microphone was denied.';
}
ignore_onend = true;
}
};
}
function talkWithApp(event) {
if (recognizing) {
recognition.stop();
message.innerHTML = 'Click "Talk" and begin speaking.';
talk_button.innerHTML = 'Talk';
return;
}
final_transcript = '';
recognition.lang = language.value;
recognition.start();
ignore_onend = false;
final_span.innerHTML = '';
interim_span.innerHTML = '';
message.innerHTML = 'Click the "Allow" button above to enable your microphone.';
start_timestamp = event.timeStamp;
}
// Speech Synthesis
function speechMyText(textToSpeech) {
var u = new SpeechSynthesisUtterance();
u.text = textToSpeech;
u.lang = language.value;
u.rate = 1.0;
u.onend = function(event) {}
speechSynthesis.speak(u);
}
.message {
color:#999;
padding: 1em 0;
}
.todo, .response {
min-height:50px;
background-color: #fff;
margin-bottom: 0.5em;
padding: 1px;
color:#555;
-webkit-box-shadow: 0 0px 3px #BDBDBD;
box-shadow: 0 0px 3px #BDBDBD;
transition: all 0.3s ease-in-out;
}
<div class="container">
<div id="message" class="message">Click "Talk" and begin speaking.</div>
<div class="todo"> <span id="final_span" class="final"></span>
<span id="interim_span" class="interim"></span>
</div>
<div class="controls">
<button id="talk_button" type="button" class="btn btn-default" onclick="talkWithApp(event)">Talk</button>
<select id="language" class="select">
<option selected="selected">Select Your Language</option>
</select>
</div>
</div>
<div class="container">
<div id="message" class="message">Click "Talk" and begin speaking.</div>
<div class="todo"> <span id="final_span" class="final"></span>
<span id="interim_span" class="interim"></span>
</div>
<div class="controls">
<button id="talk_button" type="button" class="btn btn-default" onclick="talkWithApp(event)">Talk</button>
<select id="language" class="select">
<option selected="selected">Select Your Language</option>
</select>
</div>
</div>
As you can see it doesn't work correctly on both when running multiple times. How can I make it so it only uses the section that was clicked? but still works in multiple places on a page.
Here are the two different ways:
https://jsfiddle.net/k5cm8ypg/
https://jsfiddle.net/ygpbfLso/1/

It seems that in your HTML your using ID multiple times; IDs should be unique to a certain page or frame.
Then in your script, both recognition object and your event can't properly get and assign values because an ID they're trying to access has been declared more than once.
What I did was;
Remove all the IDs to use classes
Add a global var activeButton
Bind talk event to the whole document and triggers when .talk_button is clicked.
When .talk_button is clicked, the context is set around that button. This is done with activeButton = $(this);. You will notice I used a combination of .parent(),.find() to find the elements within the context or container of that button.
Run the demo on jsfiddle. It was fun to work with, didn't know there's a speech api readily available on the browser.
https://jsfiddle.net/1pvqx2am/2/

Related

Javascript for loop not repeating strings

very new to Javascript here, and I think I'm having a logic issue. So basically for class I'm building a hangman game, and I am having trouble with double letters. for instance if the word is food, when I enter an "O" it will pass through the for loop, hit that first O, push it to the screen, and stop dead in its tracks. I can do whatever I want to that first "O" but a second one or any other repeated letter gets ignored. Now the alert I wrote directly under the start of the for() loop, will successfully print both "O's", as will logging it to the console, or even flat out writing document.write(splitWord[m]);
So to me, I think it has to be my if statement. I could be 100% wrong on this, but I assume that the if statement tells it to see the first "O", do what's in the bracket, and then move on to the next letter skipping any doubles. If I am right about this, what would be a better option to keep the loop going, so both "O's" would be filled. And if I am completely wrong, what would be a better course of action to accomplish this task. Any help would be very greatly appreciated.
Thanks
var remainingLetters = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
var removedLetters =[];
var wordList = ["django", "the#good#the#bad#and#the#ugly", "a#fistful#of#dollars","for#a#few#dollars#more","once#upon#a#time#in#the#west","the#wild#bunch","pale#rider"];
var titleList =["django", "The Good The Bad And The Ugly", "A Fistful of Dollars", "For a few Dollars More", "Once Upon a Time in the West", "The Wild Bunch", "Pale Rider"];
var songList =["Jango", "The Good The Bad And The Ugly", "Fistful of Dollars", "For a few Dollars More", "Once Upon a Time in the West", "The Wild Bunch", "Pale Rider"]
var selectedWord;
console.log(selectedWord);
var livesRemaining = 12;
var score = 0;
var wordWorth = 0;
var wins = 0;
var losses = 0;
var gameOn = false;
function chooseAWord(){
selectedWord = wordList[Math.floor(Math.random() * wordList.length)];
console.log(selectedWord);
}
function printWord(){
document.getElementById("wordDisplayer").innerHTML = selectedWord;
}
function buildTiles(){
// create a new div element
// and give it some content
var splitWord = selectedWord.split("");
for(i = 0; i < splitWord.length; i++){
if (splitWord[i] != '#'){
// var newTile = document.createElement("div");
//var newContent = document.createTextNode("");
//newTile.appendChild(newContent); //add the text node to the newly created div.
document.getElementById("wordTiles").innerHTML += '<div class="tileStyle" id="' + splitWord[i] + '"></div>';
wordWorth++;
// add the newly created element and its content into the DOM
//var currentDiv = document.getElementById("wordTiles");
//currentDiv.appendChild(newTile, currentDiv);
// newTile.setAttribute("class", "tileStyle");
}else if(splitWord[i] == '#'){
var blankTile = document.createElement("div");
var spaceContent = document.createTextNode("");
blankTile.appendChild(spaceContent);
document.getElementById("wordTiles").innerHTML += '<div class="blankStyle" id="' + splitWord[i] + '"></div>';
}
}
}
function clearTiles(){
var myNode = document.getElementById("wordTiles");
while (myNode.firstChild) {
myNode.removeChild(myNode.firstChild);
}
}
function refreshAlphabet(){
remainingLetters = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
displayAvailableLetters();
}
function keyPressed(){
checkPlayerChoiceNew();
}
var playerGuess = document.onkeyup = function myKeyDown(event){
playerGuess = event.key;
if(gameOn==true){
keyPressed();
}else{
}
}
function checkPlayerGuess(){
document.getElementById("isThisWorking").innerHTML = playerGuess;
}
// function myFunction() {
// var str = "Tha bast things in lifa ara free";
// var patt = new RegExp(playerGuess);
// var res = patt.test(selectedWord.toLowerCase());
// document.getElementById("demo").innerHTML = res;
//}
function displayAvailableLetters(){
document.getElementById("lettersStillAvailable").innerHTML = remainingLetters;
console.log(remainingLetters);
}
function displayRemovedLetters(){
document.getElementById("lettersUsed").innerHTML = removedLetters;
}
function updateScore(){
document.getElementById("scoreTotal").innerHTML = score;
}
function updateWins(){
document.getElementById("winTotals").innerHTML = wins;
}
function updateLosses(){
document.getElementById("lossTotals").innerHTML = losses;
}
function checkScore(){
if(score == selectedWord.length && livesRemaining > 0){
document.getElementById("gameOver").innerHTML = "WINNER! Congratulations!!!";
wins++;
updateWins();
gameOn=false;
}else if (livesRemaining == 0){
livesRemaining == -1;
document.getElementById("gameOver").innerHTML = "You have failed!";
losses++;
updateLosses();
gameOn=false;
}else{
document.getElementById("gameOver").innerHTML = "Good Luck!";
}
}
function checkPlayerChoiceNew(){
var splitWord = selectedWord.split("");
var choice = new RegExp(playerGuess);
var compareWord = choice.test(selectedWord.toLowerCase());
var compareAlphabet = choice.test(remainingLetters);
var compareRemovedList = choice.test(removedLetters);
for (m = 0; m < splitWord.length; m++){
//alert(splitWord[m]);
if(playerGuess == splitWord[m]){
document.getElementById(splitWord[m]).innerHTML = playerGuess;
}
}
}
//check playerGuess against selectedWord
function checkPlayerChoice(){
var choice = new RegExp(playerGuess);
var compareWord = choice.test(selectedWord.toLowerCase());
var compareAlphabet = choice.test(remainingLetters);
var compareRemovedList = choice.test(removedLetters);
if(compareWord == true && compareAlphabet == true ){
document.getElementById("demo").innerHTML = playerGuess;
remainingLetters.splice(remainingLetters.indexOf(playerGuess),1);
displayAvailableLetters();
displayRemovedLetters();
score++;
updateScore();
checkScore();
}else if(compareWord == true && compareAlphabet == false){
document.getElementById("demo").innerHTML = "Already tried that one";
}else if(compareWord == false && compareAlphabet == true){
livesRemaining--;
document.getElementById("lives").innerHTML = livesRemaining;
removedLetters.push(playerGuess.toLowerCase());
remainingLetters.splice(remainingLetters.indexOf(playerGuess),1);
updateScore();
checkScore();
displayAvailableLetters();
displayRemovedLetters();
}else if (compareWord == false && compareAlphabet == false && compareRemovedList == true){
document.getElementById("demo").innerHTML = "Already tried that one ;)";
}else if (compareWord == false && compareAlphabet == false && compareRemovedList == true){
}else{
/*livesRemaining--;
document.getElementById("lives").innerHTML = livesRemaining;
removedLetters.push(playerGuess.toLowerCase());
updateScore();
checkScore();
displayAvailableLetters();
displayRemovedLetters();*/
document.getElementById("demo").innerHTML = "Not a Valid Key";
}
}
//document.onkeyup = function myKeyDown(event){
// playerGuess = event.key;
//}
//start / Restart the game
function resetGame() {
livesRemaining = 12;
score =0;
wordWorth = 0;
clearTiles();
document.getElementById("lives").innerHTML = livesRemaining;
chooseAWord();
printWord();
buildTiles();
refreshAlphabet();
gameOn=true;
}
.tileStyle{
width:30px;
height:30px;
border:1px solid black;
background-color:green;
float:left;
margin-left:10px;
margin-right:10px;
margin-bottom:10px;
margin-top:10px;
}
.blankStyle{
width:30px;
height:30px;
background-color:orange;
float:left;
margin-left:10px;
margin-right:10px;
margin-bottom:10px;
margin-top:10px;
}
.fixer{
width:100%;
height:10px;
clear:both;
}
<body>
<button onclick="checkPlayerChoice()">Try it</button>
<p id="demo"></p>
<p> lives: </p>
<p id = "lives"> 0</p>
<p> Score: </p>
<p id = "scoreTotal">0</p>
<p>wins</p>
<p id ="winTotals">0</p>
<p>losses</p>
<p id ="lossTotals">0</p>
<p id ="gameOver"></p>
<button onclick ="resetGame()">New Game</button>
<p>Here is the word</p>
<p id = "wordDisplayer">Press New Game to Start</p>
<div id = "wordTiles"></div>
<div class ="fixer"></div>
<button onclick ="checkPlayerGuess()">What Key was Pressed?</button>
<p id ="isThisWorking">What will I say?</p>
<p>Letters Still Available</p>
<p id ="lettersStillAvailable"></p>
<p>Bad Guesses</p>
<p id ="lettersUsed"></p>
<br />
selectedWord ="food";
function checkPlayerChoiceNew(){
var splitWord = selectedWord.split("");
var choice = new RegExp(playerGuess);
var compareWord = choice.test(selectedWord.toLowerCase());
var compareAlphabet = choice.test(remainingLetters);
var compareRemovedList = choice.test(removedLetters);
for (m = 0; m < splitWord.length; m++){
//alert(splitWord[m]);
if(playerGuess == splitWord[m]){
document.getElementById(splitWord[m]).innerHTML = choice;
}
}
}
You can refer this below logic. In this example, I have given some inputs.
var selectedWord ="food";
var displayString = [];
for(var i = 0; i < selectedWord.length; i++){
displayString[i] = "-"
}
var outputEle = document.getElementById("output");
var div = document.createElement('div');
div.innerText = displayString.join(" ");
outputEle.appendChild(div);
function checkPlayerChoiceNew(playerGuess){
var newWord = "";
var regExp = new RegExp(playerGuess,'ig')
selectedWord.replace(regExp, function(value, index){
displayString[index] = value;
return value;
});
var div = document.createElement('div');
div.innerText = displayString.join(" ");
outputEle.appendChild(div);
newWord = displayString.join("");
if(selectedWord == newWord){ alert("You Won the game"); }
//outputEle.innerText = displayString.join(" ");
}
checkPlayerChoiceNew('o');
checkPlayerChoiceNew('g');
checkPlayerChoiceNew('d');
checkPlayerChoiceNew('f');
<div id="output">
</div>

what's wrong with this javascript script.?

I am trying to learn javascript by following this exercise from MDN website Learn JavaScript
here is my final code for the game.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Number guessing game</title>
<style>
html {
font-family: sans-serif;
}
body {
width: 50%;
max-width: 800px;
min-width: 480px;
margin: 0 auto;
}
.lastResult {
color: white;
padding: 3px;
}
</style>
</head>
<body>
<h1>Number guessing game</h1>
<p>We have selected a random number between 1 and 100. See if you can guess it in 10 turns or less. We'll tell you if your guess was too high or too low.</p>
<div class="form">
<label for="guessField">Enter a guess:</label>
<input type="text" id="guessField" class="guessField" autofocus>
<input type="submit" value="Submit guess" class="guessSubmit">
</div>
<div class="resultParas">
<p class="guesses"></p>
<p class="lastResult"></p>
<p class="lowOrHi"></p>
</div>
</body>
<script>
// Your JavaScript goes here
var randomNumber = Math.floor(Math.random() * 100) + 1;
var guesses = document.querySelector(".guesses");
var lastResult = document.querySelector(".lastResult");
var lowOrHi = document.querySelector(".lowOrHi");
var guessField = document.querySelector(".guessField");
var guessSubmit = document.querySelector(".guessSubmit");
var test; //used for creating new reset button
var count = 1; // counter for counting user input
function checkGuess() {
//alert('checkGuess is called');
var value = Number(guessField.value);
if (count === 1) {
guesses.textContent = "Previous guesses :"
}
guesses.textContent += value + ' ';
if (value === randomNumber) {
lastResult.textContent = "congratulation u successfully guessed the number";
lastResult.style.backgroundColor = "green";
lowOrHi.textContent = "";
left = 1;
setGameOver();
} else if (count === 10) {
lastResult.textContent = "game over"
lastResult.style.backgroundColor = "red";
left = 1;
setGameOver();
} else {
lastResult.textContent = "WRONG";
lastResult.style.backgroundColor = "red";
if (value < randomNumber) {
lowOrHi.textContent = "too low";
} else {
lowOrHi.textContent = "too high";
}
}
count++;
guessField.value = '';
}
guessSubmit.addEventListener("click", checkGuess);
function setGameOver() {
guessField.disabled = true;
guessSubmit.disabled = true;
test = document.createElement('button');
test.textContent = "restart game";
document.body.appendChild(test);
test.addEventListener('click', resetGame);
}
function resetGame() {
count = 1;
var resetParas = document.querySelectorAll('.resultParas');
for (var i = 0; i < resetParas.length; i++) {
resetParas[i].textContent = '';
}
guessField.disabled = false;
guessSubmit.disabled = false;
guessField.value = '';
lastResult.style.backgroundColor = 'white';
randomNumber = Math.floor(Math.random() * 100) + 1;
test.parentNode.removeChild(test);
}
</script>
</html>
But when i try to run the game and use the reset game button to restart the game then i am not able to manipulate guesses,lastResult and lowOrHi elements using textContent and backgroundColor properties.
Your blanking out everything inside .resultParas.. And this will include all you <p> tags. IOW: after doing that they have disappeared from the DOM, you can see this say in chrome inspector that .resultPara's after clicking reset game is now blank, and all your p tags have gone.
I think what you really want to do, is blank out the children (the p tags)..
You don't need querySelectorAll either, as in your case there is only the one.
var resetParas = document.querySelector('.resultParas');
for(var i = 0 ; i < resetParas.children.length ; i++) {
resetParas.children[i].textContent = '';
}

How can I create a variable condition as a parameter in javascript?

I want to test how many red/black/even/odd comes up in a row in the game of roulette.
The following function will loop through a list of spins n and give how many times in a row red won and lost. The same function can be used for all the other types of even wins however the check is different
color[n[i]] == "red"
I want to pass a different check into this function to test for evens
n[i]%2 == 0
Can this be done?
function test(n)
{
var wins = parseInt(0);
var losses = parseInt(0);
for(var i=0;i<n.length;i++)
{
if(color[n[i]] == "red")
{
wins += 1
losses = 0
}
else
{
wins = 0
losses += 1
}
}
.
.
.
PART 2
This is the full code. If you click the 'Enter Spins' button and the 'Toggle Number Pad' button, then add the number 8 twice, then 3 alerts will display.
I can not seem to get the the 3 messages to show up on separate lines. I tried some examples, but it always adds the line return before the last message.
Do you know how to get the multiple messages on separate lines?
<html>
<head>
<style>
.bntcal {
padding: 10px 10px 10px 10px;
margin: 10px;
}
.bntcaladd {
padding: 10px 10px 10px 10px;
margin: 10px;
}
.bntshow{
padding: 5px 5px 5px 5px;
margin: 5px;
width: 10%;
}
.spanhide {
display: none;
}
.bell {
float:left;
display: none;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
var wheel0 = [37,32,15,19,4,21,2,25,17,34,6,27,13,36,11,30,8,23,10,5,24,16,33,1,20,14,31,9,22,18,29,7,28,12,35,3,26];
var wheel00 = [37,28,9,26,30,11,7,20,32,17,5,22,34,15,3,24,36,13,1,38,27,10,25,29,12,8,19,31,18,6,21,33,16,4,23,35,14,2];
var wheel = wheel00;
var wColor = "";
var numbers = [];
var color = [];
$(document).ready(function(){
// --- Menu Buttons
$("#enterSpins").click(function(){
$("#divSpins").show();
$("#divAlerts").hide();
$("#divHowTo").hide();
});
$("#setAlert").click(function(){
$("#divAlerts").show();
$("#divSpins").hide();
$("#divHowTo").hide();
});
$("#howTo").click(function(){
$("#divHowTo").show();
$("#divSpins").hide();
$("#divAlerts").hide();
});
// ---- Sub Buttons
$("#enterPad").click(function(){
$("#showSpinsPad").toggle();
$("#clearBox").toggle();
$("#clearBox1").toggle();
if(!$("#showSpinsPad").is(":hidden"))
{
$("#spins").prop("disabled", true)
}
else
{
$("#spins").prop("disabled", false)
}
});
$(".bntcal").click(function(){
$("#currentSpin").text($("#currentSpin").text()+$(this).val())
if ($("#currentSpin").text().length > 2)
{
$("#currentSpin").text($(this).val())
}
});
$("#clear").click(function(){
$("#currentSpin").text("")
});
$("#add").click(function(){
getWheel()
currentSpin = $("#currentSpin").text()
if(currentSpin.length > 0)
{
if ($("#spins").val().length > 0)
{
$("#spins").val($("#spins").val() + ", ");
}
if(parseInt(currentSpin)<37)
{
$("#spins").val($("#spins").val() + currentSpin);
}
if(parseInt(currentSpin) == 37)
{
$("#spins").val($("#spins").val() + "0");
}
if(parseInt(currentSpin) == 38)
{
$("#spins").val($("#spins").val() + "00");
}
if(parseInt(currentSpin)>38)
{
$("#spins").val($("#spins").val() + "0");
}
$("#currentSpin").text("")
}
var n = GetUserNumbers();
run(n)
});
$("#undo").click(function(){
var n = GetUserNumbers();
if (n.length>0)
{
n.pop();
}
$("#spins").val(n)
run(n)
});
$("#clean").click(function(){
$("#spins").val("")
});
$("#run").click(function(){
var n = GetUserNumbers();
run(n)
});
});
// ---------------------------------------------------------------
// --------------------- FUNCTIONS -------------------------------
// ---------------------------------------------------------------
function run(n)
{
$("#alert").text("")
// Evens
var conditions = ['color[n] == "red"','color[n] == "black"','n%2 == 0 && n<37','n%2 == 1 && n<37','n > 18 && n<37','n < 19 && n>0']
var checklocation = ['Red','Black','Even','Odd','High','Low']
var idWins = "#evenwin"
var idLosses = "#evenloss"
checkCondition(n, conditions, checklocation, idWins, idLosses)
// Dozens
var conditions = ['n%3 == 1','n%3 == 2','n%3 == 0','n>=1 && n<=12','n>=13 && n<=24','n>=25 && n<=36']
var checklocation = ['Row 1 [1,2,3..]','Row 2 [2,3,4..]','Row 2 [3,6,9..]','Dozen 1 [1-12]','Dozen 1 [13-24]','Dozen 1 [25-36]']
var idWins = "#dozenwin"
var idLosses = "#dozenloss"
checkCondition(n, conditions, checklocation, idWins, idLosses)
}
function checkCondition(n, conditions, checklocation, idWins, idLosses)
{
for(var i=0; i<conditions.length; i++)
{
var check = function(n){ if(conditions[i]){ return true; } else { return false; }}
var wins = checkWins(n, check)
var losses = checkLosses(n, check)
if(wins >= $(idWins).val()) { $("#alert").text($("#alert").text()+" "+checklocation[i]+" loses "+wins+" times in a rows.<br/>")}
if(losses >= $(idLosses).val()) { $("#alert").text($("#alert").text()+" "+checklocation[i]+" loses "+losses+" times in a rows.<br/>")}
}
}
function checkWins(n, condition)
{
var wins = parseInt(0);
for(var i=0;i<n.length;i++)
{
if(condition(n[i]))
{
wins += 1
}
else
{
wins = 0
}
}
return wins
}
function checkLosses(n, condition)
{
var losses = parseInt(0);
for(var i=0;i<n.length;i++)
{
if(condition(n[i]))
{
losses = 0
}
else
{
losses += 1
}
}
return losses
}
$.fn.multiline = function(text){
this.text(text);
this.html(this.html().replace(/\n/g,'<br/>'));
return this;
}
function getWheel()
{
if($("input[name=wheel]:checked").val()=="0")
{
wheel = wheel0
}
else
{
wheel = wheel00
}
color = GetColor(wheel)
}
function reset()
{
evenwins = parseInt(0);
}
function GetUserNumbers()
{
var n = $("#spins").val().split(",");
for(var x=0; x<n.length; x++)
{
if(n[x].trim() == "0")
{
n[x] = "37";
}
if(n[x].trim() == "00")
{
n[x] = "38";
}
n[x] = parseInt(n[x].trim());
}
return n;
}
function GetColor(wheel)
{
var color = Array();
if(wheel.length==37)
{
color[1] = "red";
color[2] = "black";
color[3] = "red";
color[4] = "black";
color[5] = "red";
color[6] = "black";
color[7] = "red";
color[8] = "black";
color[9] = "red";
color[10] = "black";
color[11] = "black";
color[12] = "red";
color[13] = "black";
color[14] = "red";
color[15] = "black";
color[16] = "red";
color[17] = "black";
color[18] = "red";
color[19] = "red";
color[20] = "black";
color[21] = "red";
color[22] = "black";
color[23] = "red";
color[24] = "black";
color[25] = "red";
color[26] = "black";
color[27] = "red";
color[28] = "black";
color[29] = "black";
color[30] = "red";
color[31] = "black";
color[32] = "red";
color[33] = "black";
color[34] = "red";
color[35] = "black";
color[36] = "red";
color[37] = "green";
}
if(wheel.length==38)
{
color[1] = "red";
color[2] = "black";
color[3] = "red";
color[4] = "black";
color[5] = "red";
color[6] = "black";
color[7] = "red";
color[8] = "black";
color[9] = "red";
color[10] = "black";
color[11] = "black";
color[12] = "red";
color[13] = "black";
color[14] = "red";
color[15] = "black";
color[16] = "red";
color[17] = "black";
color[18] = "red";
color[19] = "red";
color[20] = "black";
color[21] = "red";
color[22] = "black";
color[23] = "red";
color[24] = "black";
color[25] = "red";
color[26] = "black";
color[27] = "red";
color[28] = "black";
color[29] = "black";
color[30] = "red";
color[31] = "black";
color[32] = "red";
color[33] = "black";
color[34] = "red";
color[35] = "black";
color[36] = "red";
color[37] = "green";
color[38] = "green";
}
return color;
}
</script>
</head>
<body>
Toggle Displays</br><br/>
<div >
<button class="bntshow" id="enterSpins">Enter Spins</button><br/>
<button class="bntshow" id="setAlert">Set Alerts</button><br/>
<button class="bntshow" id="howTo">How To</button><br/>
<input type="radio" name="wheel" value="0">0 Wheel<br/>
<input type="radio" name="wheel" value="00" checked>00 Wheel<br/>
</div><br/>
<div id="alert"></div>
<hr>
<!-- Enter Spins -->
<span class="spanhide" id="divSpins">
<button class="bntcaladd" id="enterPad">Toggle Numberpad</button><br/>
<br/>
<span class="spanhide" id='showSpinsPad'>
<br/>
<button class="bntcal" id="calculator" value="0">0</button>
<button class="bntcal" id="calculator" value="00">00</button><br/>
<button class="bntcal" id="calculator" value="1">1</button>
<button class="bntcal" id="calculator" value="2">2</button>
<button class="bntcal" id="calculator" value="3">3</button><br/>
<button class="bntcal" id="calculator" value="4">4</button>
<button class="bntcal" id="calculator" value="5">5</button>
<button class="bntcal" id="calculator" value="6">6</button><br/>
<button class="bntcal" id="calculator" value="7">7</button>
<button class="bntcal" id="calculator" value="8">8</button>
<button class="bntcal" id="calculator" value="9">9</button><br/>
<button class="bntcaladd" id="clear">Clear</button>
<button class="bntcaladd" id="add">ADD</button><span id="currentSpin"></span>
<br/>
<button class="bntcaladd" id="undo">Undo</button><br/>
<span id="currentSpin"></span>
<br/>
</span>
<span id="clearBox">Enter roulette numbers separated by a comma</span><br/>
<textarea rows="10" cols="50" id="spins"></textarea><br/><br/>
<span id="clearBox1">
<button id="clean">Clear Box</button>
<button id="run">Run</button>
</span>
</span>
<!-- Set Alerts -->
<span class="spanhide" id="divAlerts">
<h2>Evens</h2>
<input type="text" id="evenwin" value="2"> Wins in a row<br>
<input type="text" id="evenloss" value="6"> Losses in a row<br>
<br><br>
<h2>Dozens</h2>
<input type="text" id="dozenwin" value="6"> Wins in a row<br>
<input type="text" id="dozenloss" value="6"> Losses in a row<br>
<br><br>
</span>
<!-- How To -->
<span class="spanhide" id="divHowTo">
How To
</span>
</body>
</html>
Yes, absolutely!
In JavaScript, you are capable of saving functions to variables, and hence pass them around as parameters; this is one of the most powerful aspects of JavaScript. So for example, if you want to check if the color is red, you can write a condition test function that returns true/false as follows:
var checkColor = function(nElement){
var color = color(nElement);
if(color == 'red'){
return true;
}
else if(color == 'black'){
return false;
}
}
So now, you have a variable checkColor that is a function that checks if a color is red or not. Now, you can pass this function into your test function like this:
function test(n,testFunc)
{
var wins = parseInt(0);
var losses = parseInt(0);
for(var i=0;i<n.length;i++)
{
if(testFunc(n[i])) //testFunc = checkColor in this case since we passed in checkColor
{
wins += 1
losses = 0
}
else
{
wins = 0
losses += 1
}
}
test(n,checkColor); //This is where you pass in checkColor as your test func
And so for example, if we wanted to add another test for an even, we could write a function as so:
var checkEven = function(nElement){
if(nElement % 2 == 0){
return true;
}
else{
return false;
}
}
And we could simply run test using this new condition like:
test(n,checkEven);
And so from here, you should get the idea of how to create a test function and pass it into a universal test function. If you need clarification, don't hesitate to ask!
Simply pass the condition as function.
Javascript:
const myFunctionByCondition = (conditionFn) => {
const index = 10
if (conditionFn(index)) return "Condition applies"
return "Condition does not apply"
}
const val = myFunctionByCondition(i => i >= 10)
Typescript:
const myFunctionByCondition = (conditionFn: (i: number) => boolean) => {
const index = 10
if (conditionFn(index)) return "Condition applies"
return "Condition does not apply"
}
const val = myFunctionByCondition(i => i >= 10)

Highlight Keywords in a given text area based on list of words

I need some help to get my program running. Its been a week and I have only made such little progress with youtube videos and google search.
I want to design a simple web application like the on on this website http://text2data.org/Demo.
With some help i was able to find the following javascript from http://www.the-art-of-web.com/javascript/search-highlight/#withutf8 that i could modify.
I have developed how i want my interface to look like but i am stuck at achieving the primary objective of keyword highlighting.
I have therefore turned to the only community i know best to help me get through this so as to make the dead line by Monday.
MODIFIED JAVA CODE ADOPTED FROM CHIRP
// Original JavaScript code by Chirp Internet: www.chirp.com.au
// Please acknowledge use of this code by including this header.
function Hilitor(id, tag)
{
var targetNode = document.getElementById(id) || document.getElementById(SentenceIn);
var hiliteTag = tag || "EM";
var skipTags = new RegExp("^(?:" + hiliteTag + "|SCRIPT|FORM|SPAN)$");
var colors = ["#ff6", "#a0ffff", "#9f9", "#f99", "#f6f"];
var wordColor = [];
var colorIdx = 0;
var matchRegex = "";
var openLeft = false;
var openRight = false;
this.setMatchType = function(type)
{
switch(type)
{
case "left":
this.openLeft = false;
this.openRight = true;
break;
case "right":
this.openLeft = true;
this.openRight = false;
break;
case "open":
this.openLeft = this.openRight = true;
break;
default:
this.openLeft = this.openRight = false;
}
};
this.setRegex = function(input)
{
input = input.replace(/^[^\w]+|[^\w]+$/g, "").replace(/[^\w'-]+/g, "|");
var re = "(" + input + ")";
if(!this.openLeft) re = "\\b" + re;
if(!this.openRight) re = re + "\\b";
matchRegex = new RegExp(re, "i");
};
this.getRegex = function()
{
var retval = matchRegex.toString();
retval = retval.replace(/(^\/(\\b)?|\(|\)|(\\b)?\/i$)/g, "");
retval = retval.replace(/\|/g, " ");
return retval;
};
// recursively apply word highlighting
this.hiliteWords = function(node)
{
if(node === undefined || !node) return;
if(!matchRegex) return;
if(skipTags.test(node.nodeName)) return;
if(node.hasChildNodes()) {
for(var i=0; i < node.childNodes.length; i++)
this.hiliteWords(node.childNodes[i]);
}
if(node.nodeType == 3) { // NODE_TEXT
if((nv = node.nodeValue) && (regs = matchRegex.exec(nv))) {
if(!wordColor[regs[0].toLowerCase()]) {
wordColor[regs[0].toLowerCase()] = colors[colorIdx++ % colors.length];
}
var match = document.createElement(hiliteTag);
match.appendChild(document.createTextNode(regs[0]));
match.style.backgroundColor = wordColor[regs[0].toLowerCase()];
match.style.fontStyle = "inherit";
match.style.color = "#000";
var after = node.splitText(regs.index);
after.nodeValue = after.nodeValue.substring(regs[0].length);
node.parentNode.insertBefore(match, after);
}
};
};
// remove highlighting
this.remove = function()
{
var arr = document.getElementsByTagName(hiliteTag);
while(arr.length && (el = arr[0])) {
var parent = el.parentNode;
parent.replaceChild(el.firstChild, el);
parent.normalize();
}
};
// start highlighting at target node
this.apply = function(input)
{
this.remove();
if(input === undefined || !input) return;
this.setRegex(input);
this.hiliteWords(targetNode);
};
}
MY HTML PAGE
#model DataAnalyzer.Models.EnterSentence
#{
ViewBag.Title = "Data Analysis";
}
#section featured {
<section class="featured">
<div class="content-wrapper">
<hgroup class="title">
<h1>#ViewBag.Title.</h1>
</hgroup>
</div>
</section>
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Enter Sentence</title>
<script type="text/javascript" src="~/Scripts/hilitor.js"></script>
<script type="text/javascript">
function dohighlight() {
var myHilitor = new Hilitor("SentenceIn");
myHilitor.apply("badWords");
//Variable for output text
var enteredText = document.getElementById("SentenceIn").value;
//Hide analyze button
document.getElementById("highlight").style.display = 'none';
//show result text area
document.getElementById("result").style.display = 'block';
//display text in results text area
document.getElementById("result").innerHTML = myHilitor;
}
</script>
</head>
<body>
<div>
<p>
Welcome to Data Analysis, Please enter a sentence in the textbox below.
</p>
#using (Html.BeginForm())
{
<div id="sentenceOut" style=" height:auto; width:500px">
#Html.TextArea("SentenceIn")
</div>
<input id="highlight" type="button" value="Analyze" onclick="dohighlight();" /> <br />
<div id="result" style="display:none; background-color:#ffffff; float:left; min-height:200px; width:500px;">
I am some text from the box up there
</div>
<div id="goodWords" style=" background-color:#ffffff; min-height:200px; width:500px;">
Good excelent bravo awesome splendid magnificent sweet estatic plaudible love like
</div>
<div id="neutralWords" style=" background-color:#ffffff; min-height:200px; width:500px;">
lukewarm maybe meh suppose
</div>
<div id="badWords" style=" background-color:#ffffff; min-height:200px; width:500px;">
fuck shit evil damn cock bullshit hate dislike poor
</div>
<script type="text/javascript">
document.getElementById("goodWords").style.visibility = 'hidden';
document.getElementById("neutralWords").style.visibility = 'hidden';
document.getElementById("badWords").style.visibility = 'hidden';
</script>
}
</div>
</body>
</html>

Mailchimp validation conflicting with Joomla slider

I am trying to embedd Mailchimp subscribe form on my Joomla site. However, it is conflicting with my 'Gavick PhotoSlide GK2'. to prevent this happened, I need to use the 'Naked form(no css or javascript)'. This will tick the user over to the MailChimp signup page when subscribing. But is it possible to have the validation working inline and not conflicting with my slider? This is the code:
<!-- Begin MailChimp Signup Form -->
<link href="http://cdn-images.mailchimp.com/embedcode/classic-081711.css" rel="stylesheet" type="text/css" />
<style type="text/css"><!--
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
--></style>
<div id="mc_embed_signup"><form action="http://thetrustsstadium.us4.list-manage1.com/subscribe/post?u=xxx&id=xxx" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank">
<div class="indicates-required"><span class="asterisk">*</span> indicates required</div>
<div class="mc-field-group"><label for="mce-EMAIL">Email Address <span class="asterisk">*</span> </label> <input name="EMAIL" class="required email" id="mce-EMAIL" type="email" /></div>
<div class="mc-field-group"><label for="mce-FNAME">First Name <span class="asterisk">*</span> </label> <input name="FNAME" class="required" id="mce-FNAME" type="text" /></div>
<div class="mc-field-group"><label for="mce-LNAME">Last Name <span class="asterisk">*</span> </label> <input name="LNAME" class="required" id="mce-LNAME" type="text" /></div>
<div id="mce-responses" class="clear">
<div class="response" id="mce-error-response" style="display:none"></div>
<div class="response" id="mce-success-response" style="display:none"></div>
</div>
<div class="clear"><input value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button" type="submit" /></div>
</form></div>
<script type="text/javascript"><!--
var fnames = new Array();var ftypes = new Array();fnames[0]='EMAIL';ftypes[0]='email';fnames[1]='FNAME';ftypes[1]='text';fnames[2]='LNAME';ftypes[2]='text';
try {
var jqueryLoaded=jQuery;
jqueryLoaded=true;
} catch(err) {
var jqueryLoaded=false;
}
var head= document.getElementsByTagName('head')[0];
if (!jqueryLoaded) {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js';
head.appendChild(script);
if (script.readyState && script.onload!==null){
script.onreadystatechange= function () {
if (this.readyState == 'complete') mce_preload_check();
}
}
}
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://downloads.mailchimp.com/js/jquery.form-n-validate.js';
head.appendChild(script);
var err_style = '';
try{
err_style = mc_custom_error_style;
} catch(e){
err_style = '#mc_embed_signup input.mce_inline_error{border-color:#6B0505;} #mc_embed_signup div.mce_inline_error{margin: 0 0 1em 0; padding: 5px 10px; background-color:#6B0505; font-weight: bold; z-index: 1; color:#fff;}';
}
var head= document.getElementsByTagName('head')[0];
var style= document.createElement('style');
style.type= 'text/css';
if (style.styleSheet) {
style.styleSheet.cssText = err_style;
} else {
style.appendChild(document.createTextNode(err_style));
}
head.appendChild(style);
setTimeout('mce_preload_check();', 250);
var mce_preload_checks = 0;
function mce_preload_check(){
if (mce_preload_checks>40) return;
mce_preload_checks++;
try {
var jqueryLoaded=jQuery;
} catch(err) {
setTimeout('mce_preload_check();', 250);
return;
}
try {
var validatorLoaded=jQuery("#fake-form").validate({});
} catch(err) {
setTimeout('mce_preload_check();', 250);
return;
}
mce_init_form();
}
function mce_init_form(){
jQuery(document).ready( function($) {
var options = { errorClass: 'mce_inline_error', errorElement: 'div', onkeyup: function(){}, onfocusout:function(){}, onblur:function(){} };
var mce_validator = $("#mc-embedded-subscribe-form").validate(options);
$("#mc-embedded-subscribe-form").unbind('submit');//remove the validator so we can get into beforeSubmit on the ajaxform, which then calls the validator
options = { url: 'http://thetrustsstadium.us4.list-manage.com/subscribe/post-json?u=xxx&id=xxx&c=?', type: 'GET', dataType: 'json', contentType: "application/json; charset=utf-8",
beforeSubmit: function(){
$('#mce_tmp_error_msg').remove();
$('.datefield','#mc_embed_signup').each(
function(){
var txt = 'filled';
var fields = new Array();
var i = 0;
$(':text', this).each(
function(){
fields[i] = this;
i++;
});
$(':hidden', this).each(
function(){
var bday = false;
if (fields.length == 2){
bday = true;
fields[2] = {'value':1970};//trick birthdays into having years
}
if ( fields[0].value=='MM' && fields[1].value=='DD' && (fields[2].value=='YYYY' || (bday && fields[2].value==1970) ) ){
this.value = '';
} else if ( fields[0].value=='' && fields[1].value=='' && (fields[2].value=='' || (bday && fields[2].value==1970) ) ){
this.value = '';
} else {
this.value = fields[0].value+'/'+fields[1].value+'/'+fields[2].value;
}
});
});
return mce_validator.form();
},
success: mce_success_cb
};
$('#mc-embedded-subscribe-form').ajaxForm(options);
});
}
function mce_success_cb(resp){
$('#mce-success-response').hide();
$('#mce-error-response').hide();
if (resp.result=="success"){
$('#mce-'+resp.result+'-response').show();
$('#mce-'+resp.result+'-response').html(resp.msg);
$('#mc-embedded-subscribe-form').each(function(){
this.reset();
});
} else {
var index = -1;
var msg;
try {
var parts = resp.msg.split(' - ',2);
if (parts[1]==undefined){
msg = resp.msg;
} else {
i = parseInt(parts[0]);
if (i.toString() == parts[0]){
index = parts[0];
msg = parts[1];
} else {
index = -1;
msg = resp.msg;
}
}
} catch(e){
index = -1;
msg = resp.msg;
}
try{
if (index== -1){
$('#mce-'+resp.result+'-response').show();
$('#mce-'+resp.result+'-response').html(msg);
} else {
err_id = 'mce_tmp_error_msg';
html = '<div id="'+err_id+'" style="'+err_style+'" mce_style="'+err_style+'"> '+msg+'</div>';
var input_id = '#mc_embed_signup';
var f = $(input_id);
if (ftypes[index]=='address'){
input_id = '#mce-'+fnames[index]+'-addr1';
f = $(input_id).parent().parent().get(0);
} else if (ftypes[index]=='date'){
input_id = '#mce-'+fnames[index]+'-month';
f = $(input_id).parent().parent().get(0);
} else {
input_id = '#mce-'+fnames[index];
f = $().parent(input_id).get(0);
}
if (f){
$(f).append(html);
$(input_id).focus();
} else {
$('#mce-'+resp.result+'-response').show();
$('#mce-'+resp.result+'-response').html(msg);
}
}
} catch(e){
$('#mce-'+resp.result+'-response').show();
$('#mce-'+resp.result+'-response').html(msg);
}
}
}
// --></script>
<!--End mc_embed_signup-->
Sure it's possible, but there's no way to tell with just the code you posted. We'll need a link to a test page so we can take a look at the whole thing and see where the conflicts are. Before I spent a bunch of time messing with it though, I would try this component -
http://extensions.joomla.org/extensions/content-sharing/mailing-a-newsletter-bridges/13602
It comes with a sign up module and it seems to integrate pretty well with most 3rd party javascript. Try it before you do anything else, it may just work.
Otherwise you will likely have to rewrite the validation or switch to server side validation in order to fix the conflict.

Categories

Resources