Here we have a simple practice javascript game , it has a list of valid HTML colors, it picks a random color when the page is loaded , it asks you for guesses and gives you hints based on your input, when you enter the correct color , it changes the background color to the color of the answer.
when you enter the winning answer , you get an alert to tell you that you've won, for some reason the background color only changes after i press ok when the alert appears on the screen, even though the statement that changes the bg color precedes the alert.
My questions are:
(1) why is the BG color changing after i close the alert popup ?
(2)whats the correct way to make the BG color change before the alert appears on the screen?
function do_game() {
var colors = ["aqua", "beige", "deeppink" , "coral", "honeydew", "lime", "gainsboro","rebeccapurple","peru","tan"].sort();
var answer = colors[Math.floor((Math.random() * colors.length))];
var finished = 0;
var numberOfGuesses = 0;
var myBody=document.getElementsByTagName("body")[0];
console.log(answer);
while(!finished){
var input = prompt('I am thinking of one of these colors \n\n' + colors + '\n\n what color am i thinking of? ' );
if(input === null)
finished = 1;
else{
numberOfGuesses++;
checkGuess(input);
if(input === answer){
myBody.style.background=answer;
finished = 1;
alert('You are right! \n you took ' + numberOfGuesses + ' Guesses!');
}
}
}
function checkGuess(input){
if(colors.indexOf(input) === -1){
//does not recognize input
alert('I don’t recognize that color!');
}else if(input > answer){
//alphabetically higher
alert('Your input is alphabetically higher than mine!');
}else if(input < answer){
//alphabatially lower
alert('Your input is alphabetically lower than mine!');
}
}
}
The browser won't repaint the screen until the function which has updated the DOM has finished running.
alert is blocking, so prevents that function from continuing to run until you click OK.
Put the alert in another function and use setTimeout to call it in a non-blocking way.
document.body.style.background = "blue";
setTimeout(function() {
alert("Hello");
});
Related
I have a check all button on click it will select all the checkboxes. But on my display page i have 30000 checkboxes which is giving me page unresponsive on click on Check All button. Can somebody please help on this.
function js_select_all(btn,theForm){
if (btn.value == "Check All") {
var checkval = "checked";
if (js_one_row(theForm.circSelected)) {
theForm.circSelected.checked = checkval;
} else {
for (var i=0; i < theForm.circSelected.length; i++){
theForm.circSelected[i].checked = checkval;
}
}
btn.value ="Uncheck All";
}else {
if (js_one_row(theForm.circSelected)) {
theForm.circSelected.checked = false;
} else {
for (var i=0; i < theForm.circSelected.length; i++){
theForm.circSelected[i].checked = false;
}
}
btn.value = "Check All";
}
}
Can soembody help me to acheive the result in fastest way possible.I am working on a webtoolkit which supports only HTML,CSS and JS.
Break the task into smaller chunks, and run them after short delays using setTimeout
This allows the browser to remain responsive. Presumably it is not essential that the tickboxes all change state immediately? The user will presumably be happy that the computer is ticking the boxes, even if it takes a few moments, since otherwise the user would have to do it himself/herself.
Here is an example where we break it into chunks of 100 check boxes, and each chunk done at an interval of 1000 ms.
const chunkSize=100;
const intervalBetweenChunksMs = 1000;
for (var i=0; i < theForm.circSelected.length ; i+=chunkSize) {
console.log("Creating chunk starting at",i)
setTimeout(function(start){for(var j=start; j<Math.min(i+chunkSize,33); j++)
{
console.log("Doing item number", j);
theForm.circSelected[j].checked = checkval;
}
}(i),(1 + theForm.circSelected.length/chunkSize)*intervalBetweenChunksMs )
}
If this works in principle, you will probably want to try smaller intervals, so that the complete "wave" of checking is done in a reasonable timeframe.
I have put in a "1+" so that the first chunk (starting at item number 0) only occurs after one interval. If this introduces an unacceptable lag before the first visible change, then remove the "1+".
I'm practicing my javascript coding by writing a color guessing game where there is a set array of colors and one will randomly be selected as the target color. The user will then be prompted to select a color. The selection goes through some criteria and if correct the background color of the page changes to match the correct color. Those are the basics of the game. I can't even get the alerts of the code to run. I have no idea of the problem. Thank you.
Here's the code I have.
<!doctype html>
<html>
<body onload="do_game()">
<script>
alert("ok");
var colors = ["coral", "olive", "khaki", "lime", "red", "maroon", "yellow", "green", "orchid"];
var alpha_colors = colors.sort();
return alpha_colors;
var finished = false;
var guesses = 0;
function do_game(){
alert("ok so far");
var num_colors = colors.length-1;
var target = colors[math.floor.random()*num_colors]
do{
var color_guess=prompt("I am thinking of these colors \n\n"+alpha_colors+"What color am I thinking of?");
guesses += 1;
finished=checkguess();
} while(finished=false);
}
function checkguess(){
if(colors.indexOf(color_guess)=-1) {
alert("Sorry. I don't recognize your color. \n\n Please try again. ");
return false;
}
if(color_guess<target) {
alert("Sorry, your guess is not correct. \n\n Hint: your color is alphabetically lower than mine");
return false;
}
if(color_guess>target) {
alert("Sorry, your guess is not correct. \n\n Hint: your color is alphabetically higher than mine");
return false;
}
alert("Congratulations! You have guessed the color! \n\n It took you "+guesses+"guesses to finish the game! \n\n You can see the color in the background");
return true;
}
style.background-color=target
</script>
</body>
</html>
You made some beginner mistakes.
After you use "return" you end everything in the current scope. So
when you return alpha_colors at line 4 your code after that line
will never run.
Thats not how you compare strings alphabetically.
math.floor.random() is not how you make a random number. Next time
try Math.floor(Math.random()*maxNumber);
When you compare two things use == or ===. Never "="! "=" in programming is different than "=" in Math. Use "=" when you want to set value to a variable and use "==" when you want to compare two things.
alert("ok");
var colors = ["black",
"green",
"yellow"
];
var alpha_colors = colors.sort();
var finished = false;
var guesses = 0;
var target = colors[Math.floor(Math.random() * alpha_colors.length)];
function do_game() {
alert("ok so far");
var color_guess = prompt("I am thinking of these colors \n\n" + alpha_colors + "What color am I thinking of?");
guesses += 1;
checkguess(color_guess);
}
function checkguess(color_guess) {
if (color_guess == "stop") {
return false;
}
if (colors.indexOf(color_guess) == -1) {
alert("Sorry. I don't recognize your color. \n\n Please try again");
do_game();
}
if (color_guess < target) {
alert("Sorry, your guess is not correct. \n\n Hint: your color is alphabetically lower than mine");
do_game();
}
if (color_guess > target) {
alert("Sorry, your guess is not correct. \n\n Hint: your color is alphabetically higher than mine");
do_game();
}
if (colors.indexOf(color_guess) >= 0) {
alert("Congratulations! You have guessed the color! \n\n It took you " + guesses + "guesses to finish the game! \n\n You can see the color in the background");
}
document.body.style.backgroundColor = target;
}
<!doctype html>
<html>
<head>
</head>
<body onload="do_game()">
<script src="script.js"></script>
</body>
</html>
Line 4 of your script tag has a return statement:
return alpha_colors;
Return statements can only be inside of functions. Also, you are referencing the function "do_game" before you have actually defined it.
I want to change the coilor of a button on mouse click from white to red then from red back to white if click again. I tried like this:
<script language="JavaScript">
<!--
function changecolor(Id){
var series = "0";
var a = window.getComputedStyle(document.getElementById(Id)).backgroundColor;
var b = 2
if (a == "#FF4F4F") {
b = 1
}
if (b == 1) {
document.getElementById(Id).style.backgroundColor = "#FFFFFF";
}
if (b == 2) {
document.getElementById(Id).style.backgroundColor = "#FF4F4F";
}
}
//-->
</script>
It won't work. This will make the button go red in mozilla, chrome but it won't click back to white. IE says "error in page". The button HTML code is:
<input type = "button" Id = "01" value="01" onClick="changecolor('01')">
Something missing from my CSS styles. It looks like the first read (of the colour) is a null value but it does makes the button go red -in the two browsers- the way this function of mine is constructed. Then it looks like the if condition is not working properly, to see the red and make it white.
The computed style of a background colour is of the format rgb(###, ###, ###) (or variations thereof, such as different whitespace or rgba) Therefore comparing with #xxxxxx will not work.
Since you're assigning to style.backgroundColor, you can simply read back:
var elem = document.getElementById(Id);
if( elem.style.backgroundColor == "#FF4F4F") {
elem.style.backgroundColor = "#FFFFFF";
}
else {
elem.style.backgroundColor = "#FF4F4F";
}
Feel free to switch the cases around as needed (based on how it should change the first time), but this will work because the browser will keep whatever you assigned to it.
However, in general, you should have a more reliable toggle:
var elem = document.getElementById(Id);
if( elem._toggle) {
elem.style.backgroundColor = "#FFFFFF";
}
else {
elem.style.backgroundColor = "#FF4F4F";
}
elem._toggle = !elem._toggle;
This will toggle reliably.
Here's a JSfiddle of a guessing game I'm making: http://jsfiddle.net/JMqxq/13/
So far everything is working great, but the part that displays the remaining guesses isn't working the way I want it to. It starts out at 3 and goes down by one each time you have an incorrect guess, which is what I want, but once you run out of guesses I want you to revert back to level one and have the remaining guesses go back to 3 since you are starting over. It successfully starts the game over, but the display of the count gets stuck at 0 (even though it's actually back to 3). I also want the displayed guesses remaining to go back up to 3 after you get a correct guess (while moving up a level), but it doesn't. Can anyone help me fix this? Here is the actual code in question:
HTML:
<p id="result">Guess a color.</p>
<p>Remaining guesses: <span id="guesses">3</span></p>
<h2>Level <span id="level">1</span></h2>
Javascript/JQuery:
function correct(){
document.getElementById("result").innerHTML = "You are correct! Guess another color.";
level++;
reset();
}
function incorrect(){
document.getElementById("result").innerHTML = "Sorry, you are incorrect.";
guesses--;
document.getElementById("guesses").innerHTML = guesses;
if (guesses == 0){
level = 1;
reset();
document.getElementById("result").innerHTML = "Guess a color";
}
}
function reset(){
$(".box").animate({"opacity": "1"}, "slow");
guesses = 3;
temp = Math.floor((Math.random()*6)+1);
document.getElementById("level").innerHTML = level;
}
function rand(){
temp = Math.floor((Math.random()*6)+1);
$("div.box").click(function() {
if (temp == $(this).data("id")) {
correct();
} else {
$(this).animate({"opacity": "0.25"}, "slow");
incorrect();
}
});
}
You need to add
document.getElementById("guesses").innerHTML = guesses;
into your reset function.
I'm really new to JS and not a developer by any stretch of the imagination! I've got the code setup to generate a random number for me from an input box and dropdown list. Basically start at x, choose a maximum number form the DDL and calculate a random number in between. Code came from CSS Tricks and I've tweaked it to work for me and coded up the HTML page.
All works fine, but I'd like to animate the answer. At the moment it just appears, and it's less than elegant. I'd like something as simple as fading it in. But all the functions I try cause the calc to stop working and no number appears, let alone animated. Any chance of some guidance as to where in my string of code I need the animation to go?
function IsNumeric(n){
return !isNaN(n);
}
$(function(){
$("#getit").click(function() {
var numLow = $("#lownumber").val();
var numHigh = $("#highnumber").val();
var adjustedHigh = (parseFloat(numHigh) - parseFloat(numLow)) + 1;
var numRand = Math.floor(Math.random()*adjustedHigh) + parseFloat(numLow);
if ((IsNumeric(numLow)) && (IsNumeric(numHigh)) && (parseFloat(numLow) <= parseFloat(numHigh)) && (numLow != '') && (numHigh != '')) {
$("#randomnumber").text(numRand);
} else {
$("#randomnumber").text("Erm...");
}
return false;
});
$("input[type=number]").each(function(){
$(this).data("first-click", true);
});
$("input[type=number]").focus(function(){
if ($(this).data("first-click")) {
$(this).val("");
$(this).data("first-click", false);
}
});
});
Error message from the JS Console:
SyntaxError: illegal character
$(#randomnumber).fade("slow");
--^
For selectors you have to use strings: $("#randomnumber").fade("slow");