result output disappears too quickly - javascript

the correct or wrong answer outputs and quickly disappears. How do I get the answer to remain on the screen. I want to keep the html and js files separate. What I want to do later is add other phrases to the program.
INDEX.HTML
<head> </head>
<body>
<form name="myForm">
<div id ="phrase"></div>
<input type = "text" id = "textinput">
<button id="myBtn">Click here</button>
<div id ="feedback"></div>
</form>
<script src = "phraseScrambler.js"></script>
</body>
</html>
PHRASESCRAMBLER.JS
var words = ['how', 'are', 'you', 'today?'];
var correctInput = "how are you today";
var userInput = 'how are you today?';
var newWords = words.slice(0);
shuffle(newWords);
question();
function question() {
var el = document.getElementById('phrase');
el.textContent = newWords.join(' ');
document.getElementById("myBtn").onclick = checkAnswer;}
function checkAnswer() {
var elMsg = document.getElementById('feedback');
if (document.myForm.textinput.value == correctInput) {
elMsg.textContent= "correct";}
else {
elMsg.textContent= "wrong answer";}}
function shuffle(newWords) {
var counter = newWords.length, temp, index;
while (counter > 0) {
index = Math.floor(Math.random() * counter);
counter--;
temp = newWords[counter];
newWords[counter] = newWords[index];
newWords[index] = temp;}
return newWords;}

First of all don't bind click event if you want to handle form submission, forms have dedicated event called onsubmit. When form is submitted default browser behavior is to navigate to form action (in your case reload the page). You need to prevent this by returning false from the onsubmit handler.
Corrected HTML will be (I gave an id to the form):
<form name="myForm" id="myForm"> ... </form>
And then event handling will look like (note return false; in checkAnswer function):
var words = ['how', 'are', 'you', 'today?'];
var correctInput = "how are you today";
var userInput = 'how are you today?';
var newWords = words.slice(0);
shuffle(newWords);
question();
function question() {
var el = document.getElementById('phrase');
el.textContent = newWords.join(' ');
document.getElementById("myForm").onsubmit = checkAnswer;
}
function checkAnswer() {
var elMsg = document.getElementById('feedback');
if (document.myForm.textinput.value == correctInput) {
elMsg.textContent = "correct";
} else {
elMsg.textContent = "wrong answer";
}
return false;
}
function shuffle(newWords) {
var counter = newWords.length,
temp, index;
while (counter > 0) {
index = Math.floor(Math.random() * counter);
counter--;
temp = newWords[counter];
newWords[counter] = newWords[index];
newWords[index] = temp;
}
return newWords;
}
<form name="myForm" id="myForm">
<div id ="phrase"></div>
<input type = "text" id = "textinput" />
<button>Click here</button>
<div id ="feedback"></div>
</form>

Related

How do I adjust the code so that the image appears when the website loads and the guess is guessing what I want it to guess?

<!DOCTYPE html>
<html>
<body>
<p id="Image"></p>
Basically what im tryijngto do s
One fix I'd recommend would be splitting your logic into two functions, one the user clicks to check their answer, and one they click to see the next question. This will allow you to display the congrats message on the screen rather than in an alert. Here is that in action:
let score = 0;
let questionsAsked = 0;
const button = document.querySelector('button');
const input = document.getElementById('userInput');
const gameScore = document.getElementById('game-score-inner');
gameScore.add = (pts = 1) => gameScore.innerHTML = parseInt(gameScore.textContent) + 1;
gameScore.subtract = (pts = 1) => gameScore.innerHTML = Math.max(parseInt(gameScore.textContent) - 1, 0);
const checkMessage = document.getElementById('check-message');
checkMessage.set = message => checkMessage.innerHTML = message;
checkMessage.clear = message => checkMessage.innerHTML = '';
const options = {
chad: 'https://via.placeholder.com/600x400/000000/efebe9/?text=Chad',
bob: 'https://via.placeholder.com/600x400/000000/efebe9/?text=Bob',
john: 'https://via.placeholder.com/600x400/000000/efebe9/?text=John'
}
function askQuestion() {
checkMessage.clear();
input.value = '';
const optionsNames = Object.values(options);
const randomPhoto = optionsNames[Math.floor(Math.random() * optionsNames.length)];
document.getElementById('image').innerHTML = `<img src="${randomPhoto}" id="question-image" width="250" height="250" />`;
button.setAttribute('onclick','checkAnswer()');
button.textContent = 'Check Your Answer!';
}
function checkAnswer() {
const userGuess = options[input.value.toLowerCase()];
const correctAnswer = document.getElementById('question-image').getAttribute('src');
if (options[input.value.toLowerCase()] === correctAnswer) {
checkMessage.set('CONGRATULATIONS!!! YOU GUESSED IT RIGHT');
gameScore.add();
} else {
checkMessage.set('SORRY, IT WAS INCORRECT');
gameScore.subtract();
}
questionsAsked++;
button.setAttribute('onclick','askQuestion()');
button.textContent = 'Next Question';
}
askQuestion();
<p id="image"></p>
<p id="game-score">Score: <span id="game-score-inner">0</span></p>
<button onclick="checkAnswer()">Start Game!</button>
<input id="userInput" type="text" />
<p id="check-message"></p>
If you would prefer to keep everything in one function and use alerts for the congrats message, you can do so by keeping track of then number of questions asked, and not instantly checking the answer on the first load, like this:
let score = 0;
let questionsAnswered = -1;
const imageContainer = document.getElementById('image');
const button = document.querySelector('button');
const input = document.getElementById('user-input');
const gameScore = document.getElementById('game-score-inner');
gameScore.add = (pts = 1) => gameScore.innerHTML = parseInt(gameScore.textContent) + 1;
gameScore.subtract = (pts = 1) => gameScore.innerHTML = Math.max(parseInt(gameScore.textContent) - 1, 0);
const options = {
chad: 'https://via.placeholder.com/250x250/000000/efebe9/?text=Chad',
bob: 'https://via.placeholder.com/250x250/000000/efebe9/?text=Bob',
john: 'https://via.placeholder.com/250x250/000000/efebe9/?text=John'
}
function askQuestion() {
questionsAnswered++;
const optionsNames = Object.values(options);
const randomPhoto = optionsNames[Math.floor(Math.random() * optionsNames.length)];
if (questionsAnswered) {
const userGuess = options[input.value.toLowerCase()];
const correctAnswer = document.getElementById('question-image').getAttribute('src');
if (options[input.value.toLowerCase()] === correctAnswer) {
gameScore.add();
alert('CONGRATULATIONS!!! YOU GUESSED IT RIGHT');
} else {
gameScore.subtract();
alert('SORRY, IT WAS INCORRECT');
}
questionsAnswered++;
}
imageContainer.innerHTML = `<img src="${randomPhoto}" id="question-image" width="250" height="250" />`;
input.value = '';
}
askQuestion();
<p id="image"></p>
<p id="game-score">Score: <span id="game-score-inner">0</span></p>
<button onclick="askQuestion()">Check Answer!</button>
<input id="user-input" type="text" />
Both solutions would work fine with alerts, though the first solution offers some greater flexibility for any functions you make want to perform in between questions. One other main fix there was to make here was to check change the image after checking the answer, and also making sure to actually fun the function in the beginning using askQuestion() in this case. I also added a couple of handy functions gameScore.add() and gameScore.subtract() to ease future use.
You can pass in other integers such as gameScore.add(2) if you every wanted to have double-weighted questions. I also added a Math.max() line to ensure the score never passes below 0. You can remove this if you would like the player's score to pass into negative numbers.
Here is a working version of your game. To begin: <br>
1.Your code was not modifying the src of the image (thus no image appears) <br>
1a. I am modifying the src attribute associated with the `img` tag now. <br>
1b. `document.getElementById("Image").src = randomPhoto;` <br>
2. `theArrayArray` does not exist. I updated the variable to `theArray` <br>
3. To display an image when the game begins you need a handler. <br>
3a. I added the `button` to handle that <br>
4. Unless you want the user to type out `.jpg` you need to remove .jpg <br>
4a. `randomPhoto = randomPhoto.replace(".jpg", "");` <br>
<img id="Image" src="#" width="250" height="250">
<br>
<br>
<input id="userInput" type="text">
<br>
<br>
<button type="button" id="btn" onclick="startGame()">Start Game</button>
<span id="GameScore">Score:</span>
<script>
let score = 10;
var Chad = "Chad.jpg";
let begin = 1;
let thePhoto;
var someArray = [ Chad, Bob
];
function startGame() {
if (start == 0) {
for (var l = 2; i < 3; i--) {
randomPhoto = theArray[Math.floor(Math.random()*theArray.length)];
document.getElementById("Image").src = randomPhoto;
document.getElementById("btn").innerHTML = "Submit";
start = 1;
}
} else {
randomPhoto = randomPhoto.replace(".jpg", "Insert");
}
else {
for (var x = 0; i < 3; i++) {
TheName = theArray[Math.floor(Math.random()*theArray.length)];
document.getElementById("Image").src = theName;
alert("No");
scorex = score-1;
}
document.getElementById("theScore").innerHTML="Score: "+score;
</script>
</body>
</html>

Basic Javascript onclick

here's my code, brand new to coding trying to get the box "points" to return the sum of pointSum if "Ben" is typed into the box "winner". Just trying to work on some basics with this project. Attempting to make a bracket of sorts
<HTLML>
<head>
<script>
var pointSum = 0;
var firstRound = 20;
var secondRound = 50;
var thirdRound = 100;
var fourthRound = 150;
var fifthRound = 250;
var finalRound = 300;
var winnerOne = false;
var winnerTwo = false;
var winnerThree = false;
var winnerFour = false;
var winnerFive = false;
var winnerSix = false;
if (winnerOne = true){
pointSum+=firstRound
} else if (winnerTwo = true){
pointSum+=secondRound
} else if (winnerThree = true){
pointSum+=thirdRound
} else if (winnerFour = true){
pointSum+=fourthRound
} else if (winnerFive = true){
pointSum+=fifthRound
} else if (winnerSix = true){
pointSum+=finalRound
else
function tally() {if document.getElementById('winner') == "Ben" { winnerOne = true;
}
pointSum=document.getElementById("points").value;
}
</script>
</head>
<body>
<form>
Winner:
<input type="text" name="winner" id="winner" size="20">
Points:
<input type="text" name="points" id="points" size="20">
Submit
<button type= "button" onclick="tally()">Tally points</button>
</form>
</body>
</html>
UPDATE***** new code, getting better, not returning console errors but still not getting anything in the "points" box upon clicking tally
<HTLML>
<head>
<script>
var pointSum = 0;
var firstRound = 20;
var secondRound = 50;
var thirdRound = 100;
var fourthRound = 150;
var fifthRound = 250;
var finalRound = 300;
var winnerOne = false;
var winnerTwo = false;
var winnerThree = false;
var winnerFour = false;
var winnerFive = false;
var winnerSix = false;
function tally() {
var winner = document.getElementById("winner").value;
var firstWinner = "Ben";
if (winner == firstWinner){
winnerOne == true;
}
pointSum = document.getElementById("points").value;
}
if (winnerOne == true){
pointSum+=firstRound;
} else if (winnerTwo){
pointSum+=secondRound;
} else if (winnerThree){
pointSum+=thirdRound;
} else if (winnerFour){
pointSum+=fourthRound;
} else if (winnerFive){
pointSum+=fifthRound;
} else if (winnerSix){
pointSum+=finalRound;
}
</script>
</head>
<body>
<form>
Winner:
<input type="text" name="winner" id="winner" size="20">
Points:
<input type="text" name="points" id="points" size="20">
Submit
<button type= "button" onclick="tally()">Tally points</button>
</form>
<div class="updatePoints">
</div>
</body>
</html>
Your code has a few mistakes, lets change it a little bit!
First, you need to access 'value' atribbute of your winner element in your if statement, and surround all the statement in parenthesis
function tally() {
if (document.getElementById('winner').value == "Ben"){
winnerOne = true;
}
pointSum = document.getElementById("points").value;
}
Second, you use '==' to make comparison, you are using '=', it means that you are assign true to variables, and you're forgetting to put ';' at the end of lines! change this part:
if (winnerOne == true){
pointSum+=firstRound;
}
put all of your if/else like the example above!
Hint: when you are using if statement you can use like this:
if (winnerOne){ //you can omit == true, because if winnerOne is true, it will enter ind the if statement
//will enter here if winnerOne is true
}
if (!winnerOne){ //you can omit == false, because if winnerOne is not true, it will enter ind the if statement
//will enter here if winnerOne is false
}
You also have a left over else at the end of your if check which is invalid. You need to end the last else if statement with the };.
Are you trying to out put the text somewhere? I don't see any code that is handling this - you may want to add some HTML that will update like so:
<div class="updatePoints">
// leave empty
</div>
Then within your JavaScript you can always add some code to update the .updatePoints
var points = document.getElementByClass('updatePoints');
points.innerHTML = pointSum.value;
Have add some lines in your code and modify it with some comments. Can try at https://jsfiddle.net/8fhwg6ou/. Hope can help.
<HTLML>
<head>
<script>
var pointSum = 0;
var firstRound = 20;
var secondRound = 50;
var thirdRound = 100;
var fourthRound = 150;
var fifthRound = 250;
var finalRound = 300;
var winnerOne = false;
var winnerTwo = false;
var winnerThree = false;
var winnerFour = false;
var winnerFive = false;
var winnerSix = false;
function tally() {
var winner = document.getElementById("winner").value;
var firstWinner = "Ben";
if (winner == firstWinner){
winnerOne = true; // Use only one = symbol to assign value, not ==
pointSum = Number(document.getElementById("points").value); // moved from outside and convert to number
// This code will update point in Points box
document.getElementById("points").value = tally_pointsum(pointSum);
// The codes below will add the text in div, just remove the + sign if you don't like
document.getElementById("updatePoints").innerHTML += (tally_pointsum(pointSum) - pointSum) + " points added<br />";
}
}
// Wrap codes below become a function, lets call it tally_pointsum:
function tally_pointsum(pointSum) {
if (winnerOne == true){
pointSum+=firstRound;
} else if (winnerTwo){
pointSum+=secondRound;
} else if (winnerThree){
pointSum+=thirdRound;
} else if (winnerFour){
pointSum+=fourthRound;
} else if (winnerFive){
pointSum+=fifthRound;
} else if (winnerSix){
pointSum+=finalRound;
}
return pointSum; //return the sum to caller
}
</script>
</head>
<body>
<form>
Winner:
<input type="text" name="winner" id="winner" size="20">
Points:
<input type="text" name="points" id="points" size="20">
Submit
<button type= "button" onclick="tally()">Tally points</button>
</form>
<!-- change class="updatePoints" to id="updatePoints" for document.getElementById("updatePoints") -->
<div id="updatePoints">
</div>
Happy coding.

how to Grey out and disable a button after its been pressed once?

hi i am trying to grey out and disable a button (each button in the div) after its been pressed once. so that the user wont be able to press it again until he/she refresh the page. hope my question is the right way to ask.. and i hope you can understand me.
this is my HTML page code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/html">
<head>
<!--this name will be visible on the tab-->
<title>Multiplayer</title>
<!--this is to link HTML and CSS together-->
<link rel="stylesheet" type="text/css" href="Hangman.css">
<script> var currentPlayingWord = "<?php echo $result["word"] ?>" </script>
<script src="jquery-1.11.3.js"></script>
<script src="JSforMultiPlayer.js"></script>
</head>
<body style="background-color:#00FFFF">
<!--this is the picture on the webpage-->
<img id="hangman-image" src="hangmanImage.png" alt="Hangman" style="width:660px;height:618px;" align="right">
<!--these are the buttons which use to input the words in-->
<div id="all-the-buttons">
<div id="first-row" class="row-button">
<button type="button">Q</button>
<button type="button">W</button>
<button type="button">E</button>
<button type="button">R</button>
<button type="button">T</button>
<button type="button">Y</button>
<button type="button">U</button>
<button type="button">I</button>
<button type="button">O</button>
<button type="button">P</button>
</div>
<div id="second-row" class="row-button" >
<button type="button">A</button>
<button type="button">S</button>
<button type="button">D</button>
<button type="button">F</button>
<button type="button">G</button>
<button type="button">H</button>
<button type="button">J</button>
<button type="button">K</button>
<button type="button">L</button>
</div>
<div id="third-row" class="row-button" style="padding-top: 4px;">
<button type="button">Z</button>
<button type="button">X</button>
<button type="button">C</button>
<button type="button">V</button>
<button type="button">B</button>
<button type="button">N</button>
<button type="button">M</button>
<button id="reset-button" type="button">RESET</button>
</div>
<p class="mylives" type="text"></p>
</div>
<form>
<input type="text" id="word-outcome"/>
</form>
<form>
<input type="text" id="wrong-guesses"/>
</form>
<form>
<input type="text" class="hint" style="display:none;" value="Hint: word is computer related." readonly></input>
</form>
<TABLE BORDER="5" WIDTH="20%" CELLPADDING="5" CELLSPACING="2" id="Score-Board">
<TR>
<caption id="table-title">Score Board</caption>
</TH>
</TR>
<TR ALIGN="CENTER">
<TH colspan="2" id="player1"></TH>
<TH colspan="2" id="player2"></TH>
</TR>
<TR ALIGN="CENTER">
<TH colspan="2" id="player1Score"></TH>
<TH colspan="2" id="player2Score"> </TH>
</TR>
</TABLE>
</body>
this is my JavaScript Code:
var wordbank = ['browser', 'binary', 'cache', 'cookie', 'CSS', 'HTML', 'javascript', 'gigabyte', 'google', 'download']
var underscores = "";
var guessCounter = 0;
var score = 1000;
var player1Name;
var player2Name;
$(document).ready(function () {
getPlayerNames();
underscores = wordloop(currentPlayingWord);
wordOutCome(underscores);
guessCounter = 10;
$('#all-the-buttons button').click(function () {
letterPress($(this));
});
});
var wordloop = function (word) {
var wordcount = 0
var underscores = "";
while (wordcount < word.length) {
underscores = underscores + "_";
wordcount++;
}
return underscores;
}
var randomNumber = function () {
var random = Math.floor((Math.random() * 9) + 0);
return random;
}
var wordOutCome = function (underscores) {
var wordoutcome = document.getElementById('word-outcome');
wordoutcome.value = underscores;
}
function letterPress(button) {
var text = button.text();
if ("RESET" === text) {
resetButton();
}
else {
var result = isLetterInWord(text, currentPlayingWord);
if (result == true) {
increaseScore();
replaceDashesForLetter(text);
var hasDashes = noMoreDashes();
if (hasDashes == true) {
navigateToWinnerPage();
}
}
else {
decreaseGuessCount();
decreaseScore();
noMoreGuesses();
addIncorrectGuessToWrongGuesses(text);
noMoreLives();
}
$('#word-outcome').val(underscores);
}
}
function isLetterInWord(guess, word) {
var uppercaseGuess = guess.toUpperCase();
var uppercaseWord = word.toUpperCase();
for (var i = 0; i < uppercaseWord.length; i++) {
console.log(i);
if (uppercaseWord[i] === uppercaseGuess) {
return true;
}
//get letter from word
//is letter from word the same as guess
//if letter from word is the same as guess return true
//return false if guess is not in the word
}
return false;
}
function replaceDashesForLetter(letter) {
for (var i = 0; i < currentPlayingWord.length; i++) {
console.log(currentPlayingWord);
var playingLetter = currentPlayingWord[i];
var upperCaseCurrentLetter = playingLetter.toUpperCase();
if (upperCaseCurrentLetter == letter) {
underscores = setCharAt(underscores, i, letter);
}
}
//for each letter in current word being played
//does letter guessed match the letter in the current word
//if letter guessed matches the letter in the current word - then replace the dash at the index (count in loop) with the letter guessed
//for each of the letters in the word being played there is a dash
//if the letter is at the index of a dash then replace that dash with the letter (which is the users guess)
}
function setCharAt(str, index, chr) {
//get first part of word up to character we want to replace
var first = str.substr(0, index);
//get second part of word ONE letter AFTER character we want to replace
var second = str.substr(index + 1);
//result is the first part plus the character to replace plus the second part
return first + chr + second;
}
var addIncorrectGuessToWrongGuesses = function (guess) {
var currentText = document.getElementById("wrong-guesses").value;
document.getElementById("wrong-guesses").value = currentText + guess;
//As the guess is wrong
//add the guess to the list of incorrect guesses displayed on the screen
}
var greyOutButton = function (button) {
//grey out the button
//make sure that the user cannot press the button anymore
}
function resetButton() {
location.href = "HangmanHomePage.php";
//Send user to the home page
}
var decreaseGuessCount = function () {
guessCounter = guessCounter - 1;
if (guessCounter === 3) {
showHint();
}
//guess count should be decreased by one
}
var noMoreGuesses = function () {
if (guessCounter === 0) {
location.href = "Looser Page.php";
}
//do something when no more guesses (navigate to loser page)
}
var noMoreDashes = function () {
var i = underscores.indexOf("_");
if (i > -1) {
return false;
}
return true;
//if index of '_' is not -1 then there are dashes
}
var navigateToWinnerPage = function () {
location.href = "Winner Page.php?score="+score;
}
var noMoreLives = function () {
var showLives = "You have " + guessCounter + " lives";
var test = document.getElementsByClassName("mylives");
test.textContent = showLives;
}
function showHint() {
document.getElementsByClassName('hint').style.display = "block";
}
function increaseScore(){
score = score + 100;
console.log(score);
var showScore = $("#player1Score");
showScore.text(score);
}
function decreaseScore(){
score = score - 100;
console.log(score);
var showScore = $("#player1Score");
showScore.text(score);
}
function navigateToDifficultyForMultiPlayer() {
//set player names in session
setPlayerNames();
//navigate to DifficultyForMultiPlayer page
location.href = "DifficultyForMultiPlayer.html";
}
function setPlayerNames() {
var firstPlayerName = document.getElementById("playerOneName").value;
var secondPlayerName = document.getElementById("playerTwoName").value;
console.log(firstPlayerName + " " + secondPlayerName);
sessionStorage.setItem("Player1Name", firstPlayerName);
sessionStorage.setItem("Player2Name", secondPlayerName);
}
function getPlayerNames(){
player1Name = sessionStorage.getItem("Player1Name");
player2Name = sessionStorage.getItem("Player2Name");
console.log(player1Name + " " + player2Name);
document.getElementById("player1").innerHTML = player1Name;
document.getElementById("player2").innerHTML = player2Name;
}
function displayScore () {
var playerOneScore = score;
}
I needed to do this recently. But what I did was, disable the button for only a few seconds so that it's long enough to prevent double clicking and short enough to still carry on if any validation errors etc.
<script type="text/javascript">
$(document).on('click', ':button', function (e) {
var btn = $(e.target);
btn.attr("disabled", "disabled"); // disable button
window.setTimeout(function () {
btn.removeAttr("disabled"); // enable button
}, 2000 /* 2 sec */);
});
</script>
If you want the button to stay disabled use this
<script type="text/javascript">
$(document).on('click', ':button', function (e) {
var btn = $(e.target);
btn.attr("disabled", "disabled"); // disable button
});
</script>
In the click function you can do this:
$("button").click(function() {
var buttonId = this.id;
document.getElementById("buttonId").disabled = true; //OR
document.getElementById("buttonId").readOnly= true;
});
You can make use of the disabled attribute :
$('#all-the-buttons button').click(function (e) {
if ($(this).is(':disabled')) e.preventDefault();
else letterPress($(this));
});
var greyOutButton = function (button) {
button.prop('disabled', true);
}
Target it with CSS to change the style :
button:disabled {
background: #F5F5F5;
color : #C3C3C3;
}
You should rethink some of your logic.
Try something like this (didn't test this)
JavaScript
$scope.letters = "qwertyuiopasdfghjklzxcvbnm";
$scope.lettersArray = [];
for (var i=0 ; i<$scope.letters.length ; i++) {
$scope.lettersArray.push($scope.letters[i];
}
$scope.disableMe = function(event) {
$(event.currentTarget).css('disabled', 'true');
}
HTML
<div ng-repeat="letter in lettersArray">
<button type="button" ng-click="disableMe($event)">{{letter}}</button>
</div>
Just add an attribute with jQuery (with adding css for cursor if you like)
$(document).ready(function () {
$("button").attr("disabled", "disabled").css("cursor", "not-allowed");
});
or simple javascript:
document.getElementsByTagName("button")[0].setAttribute("disabled", "disabled");

Adding an event listener using an object’s property

What I want to have is a working button and input form for my code which is a block in an object literal. My form shows fine when I run the code, but doesn’t output a value. Why not?
<input class="number" type="number" placeholder="Enter some number...">
<button>enter</button>
<p id="output"></p>
<script>
var input = document.querySelector("#number");
var output = document.querySelector("#output");
var button = document.querySelector("button");
add.button.addEventListener("click", add.number, false);
button.style.cursor = "pointer";
var add = {
number: function () {
amount = parseInt(input.value);
if (amount == 5) {
output.innerHTML = alert("true");
} else {
output.innerHTML = alert("false");
}
}
};
</script>
You have to define the function before you can pass it to addEventListener otherwise you are just passing undefined.
<input class="number" type="number" placeholder="Enter some number..." id="number">
<button id="button">enter</button>
<p id="output"></p>
var input = document.getElementById("number");
var output = document.getElementById("output");
var add = {
number: function () {
amount = parseInt(input.value, 10);
if (amount === "5") {
alert("true");
output.innerHTML = true;
} else {
alert("false");
output.innerHTML = false;
}
}
};
var button = document.getElementById("button");
button.addEventListener("click", add.number, false);
button.style.cursor = "pointer";
See: http://jsfiddle.net/zw7e7q72/

how to do a printer-like text field using javascript OOP

I'm doing a printer-like text field which could show the letter one by one. I could realize it just use a function and load it as simple like:
html---
<div id="myTypingText"></div>
js---
<script>
var myString = "Place your string data here, and as much as you like.";
var myArray = myString.split("");
var loopTimer;
function frameLooper() {
if(myArray.length > 0) {
document.getElementById("myTypingText").innerHTML += myArray.shift();
} else {
clearTimeout(loopTimer);
return false;
}
loopTimer = setTimeout('frameLooper()',70);
}
frameLooper();
</script>
But I want to do more advanced, I want to let the user to change the speed and change the text, so I wrote the following one but it went wrong, why? help me .thx.
html----
<div id="myTypingText"></div>
<p>Enter the tempo:</p><input type="text" id="tempo" value="70">
<p>Enter the Text:<p><input type="text" id="text" value="abcdefghijklmn">
<button onclick="begin()">Begin</button>
js----
<script type="text/javascript">
function Printer(){
this.myString = document.getElementById("text").value;
this.myArray = this.myString.split("");
this.tempo = document.getElementById("tempo").value;
this.len = this.myArray.length;
this.loop = function (){
if(this.len > 0 ){
document.getElementById("myTypingText").innerHTML += this.myArray.shift();
}
}
}
function begin(){
var test = new Printer();
setInterval(test.loop,test.tempo);
}
</script>
You need to use an anonymous function in the interval if you want the loop function to be executed in the context of the Printer object. Also you need to check the length of the array each time as the len property won't be updated when the array is shifted.
function Printer() {
this.myString = document.getElementById("text").value;
this.myArray = this.myString.split("");
this.tempo = document.getElementById("tempo").value;
this.loop = function () {
if (this.myArray.length > 0) {
document.getElementById("myTypingText").innerHTML += this.myArray.shift();
}
}
}
function begin() {
var test = new Printer();
setInterval(function () {
test.loop()
}, test.tempo);
}
See the working fiddle
Here's another approach. Your fundamental problem was with using the this keyword. You have to remember that when you enter another function scope, the this keyword changes. You'll notice here that I cache or save 'this' to equal that, then use that new 'that' value in the function. Plunker
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="myTypingText"></div>
<p>Enter the tempo:</p><input type="text" id="tempo" value="70">
<p>Enter the Text:<p><input type="text" id="text" value="abcdefghijklmn">
<button onclick="begin()">Begin</button>
<script type="text/javascript">
function Printer(){
this.myString = document.getElementById("text").value;
this.myArray = this.myString.split("");
this.tempo = document.getElementById("tempo").value;
this.len = this.myArray.length;
var that = this;
this.loop = function (){
if(that.myArray.length !== 0 ){
document.getElementById("myTypingText").innerHTML += that.myArray.shift();
}
}
}
function begin(){
var test = new Printer();
setInterval(test.loop,test.tempo);
}
</script>
</body>
</html>

Categories