How do I display text using jQuery without having it disappear?
When the user types in a number. I then want to display a certain message - You're hot cold warm etc. Right now the message flashes into the screen, but I want it to stay and then the user can continue playing until he gives up and wants to display the random number or reset the game.
The only thing relevant in the html is:
<div class="output-container">
</div>
which is where I want to display the message.
Here is the application.js:
// Hot or Cold JS game.
$(document).ready(function() {
var randomNumber = Math.floor((Math.random() * 100 ) + 1);
$('#Enter').click(function() {
var guessNumber = document.getElementById('number');
var difference = Math.abs(guessNumber - randomNumber);
if (difference == 0) {
// Display to user - "Perfect"
$('.output-container').append('Perfect');
} else if (difference < 5) {
// Display to user - You're on Fire!
$('.output-container').append('You are on Fire!');
} else if (difference < 10) {
// Display to user - Warm
$('.output-container').append('Warm');
} else if (difference < 30) {
// Display to user - Ice Cold
$('.output-container').append('Ice Cold');
} else {
// Display to user - You must be Frozen?
$('.output-container').append('You must be Frozen!');
};
});
// Start over
$('#reset').click(function() {
location.reload();
});
$('#show').click(function() {
$('#show').hide();
$('#append-number').append(randomNumber);
});
});
Quick demo
Changes to Javascript:
var guessNumber = document.getElementById('number').value;
...
// $('.output-container').append(...) // BAD
$('.output-container').text(...) //GOOD
And either make #Enter be a plain type="button" or add return false; at the end of the .click() handler. Otherwise it's going to keep submitting and reloading the page.
It is exactly as I assumed, you have the buttons inside the form and clicking them reloads the page. Change the type of the button to button:
<button type="button" ... >Enter</button>
or prevent the default event (submitting the form) from taking place:
$('#Enter').click(function(event) {
event.preventDefault();
});
However, if you don't want to use the "Enter" button as submit button, don't specify it as one.
Note that there are other problems with your code, but that's out of the scope of this question.
Related
I am second semester, taking a class in Javascript. Basically, we were given the HTML and CSS for a website, and it is supposed to do the following:
It's a number game. The computer generates a number, and you have ten tries to guess this number. If you get to zero, the computer wins, and there is a reset button which should reset all the variables and start again. Only problem is, I cannot for the life of me figure out how to reset the countDown variable after the score reaches 0. Please help. Also we are using only pure Javascript for this course for now. I don't want to cheat, I am more trying to figure out what the issue is that's holding me back.
var countDown = 10;
var computerNumber = Math.floor((Math.random() * 501) + 1);
function generate() {
playerNumber = document.getElementById("guess").value;
if (computerNumber == playerNumber && countDown > 0) {
alert("Congratulations! You've won!");
} else if (playerNumber < computerNumber && countDown > 0) {
countDown--;
document.getElementById("guesses").value = countDown;
document.getElementById("result").value = "Too Low";
} else if (playerNumber > computerNumber && countDown > 0) {
countDown--;
document.getElementById("guesses").value = countDown;
document.getElementById("result").value = "Too High";
} else if (countDown == 0) {
alert("Game Over. The Number Was " + computerNumber);
}
}
function reset() {
countDown = 10;
computerNumber = Math.floor((Math.random() * 501) + 1);
}
In the reset function, you would need to update the element that displays the countDown in the HTML
Here you need to add the reset button in the html:
<input type="button" class="reset-button" value="Reset Count">
Then grab that button in your JS below the reset function and attach an eventListener that fires the reset function when clicked:
const resetBtn = document.querySelector('.reset-button')
resetBtn.addEventListener('click', reset )
And that's it.
You would probably want the count displayed on the page, too. You could add a line in the reset function that pushes the new value of countDown into the html (with element.textContent = countDown.toString(), for example)
If you take a JS class in 2021 you should definitely use const and let instead of var, and let your teacher know why. Using var works, though, but will show a future employer that you're out of touch with what's going on in the JS world.
I'm writing a choose your own adventure program where If a specific option is chosen (example to wait) the user gets a random number between 1-10 to do push ups(the push-ups would be the user clicking on the prompt "ok" button however many times the random number is equal to) here's my code so far but I keep getting errors. I'm a complete noob so go easy on me.
var count = Math.floor((Math.random() * 10) + 1);
var setsOf10 = false;
function pushUps() {
alert("Nice! Lets see you crank out " + pushUps + "!");
}
if (setsOf10 == pushUp) {
alert("Nice! Lets see you crank out " + pushUp + "!");
setsOf10 = true;
}
for (var i=0; i<count; i++){
pushUps();
}
else {
alert("Really, thats it? Try again");
}
while ( setsOf10 == false);
}
After playing with this some more I can tell i'm close but still don't have it. and again, I'M NOT ASKING YOU TO SOLVE THIS FOR ME JUST NEED POINTERS AS TO WHAT IM DOING WRONG OR MISSING. Here's what I have, Its giving me my random number I just need it to allow me to click the "ok" button however many times the random number has assigned me.
var pushUpSets = Math.floor((Math.random() * 10) + 1);
function pushUps(){
alert(pushUpSets);
if (pushUpSets < 3){
var weak = "Thats it? Weak sauce!";
alert(weak);
}
else{
alert("Sweet lets get some reps in!");
}
for (i=0; i>3; i++){
pushUps(pushUpSets);
}
}
Here, the make a choice button is just dummy to allow us to go to do push ups. Each click decrements our count.
// This is important, we use this event to wait and let the HTML (DOM) load
// before we go ahead and code.
document.addEventListener('DOMContentLoaded', () => {
document.querySelector('#choice').addEventListener('click', makeChoice);
});
function makeChoice() {
// Call a method to set random pushups and setup the click event
setUpPushUp();
// Here we change the display style of the push up section so that it shows to the player.
document.querySelector('.activity').style.display = 'block';
}
// The pushups variable is declared at the document level
// This way our setUpPushUp and doPushUp functions have easy access.
let pushUps = 0;
function setUpPushUp() {
// Create a random number of pushups, in sets of 10.
// We add an extra 1 so we can call the doPushUp method to initialize.
pushUps = (Math.floor((Math.random() * 10)+1)*10)+1 ;
// Add a click event to the push up button and call our doPushUp method on each click.
document.querySelector('#push').addEventListener('click', doPushUp);
// This is just an init call, it will use the extra 1 we added and place test in our P tag.
doPushUp();
}
function doPushUp() {
// Get a reference to our output element, we will put text to player here.
let result = document.querySelector('p');
// They have clicked, so remove a push up.
pushUps--;
// See if the player has done all the required push ups (i.e. pushUps is 0 or less.)
if (pushUps > 0) {
result.innerText = `You need to crank out ${pushUps} pushUps`;
} else {
result.innerText = 'Nice work!';
}
}
.activity {
display: none;
}
<button id="choice">Make a choice !</button>
<div class="activity">
<p></p>
<button id="push">Push</button>
</div>
I am trying to create a basic gallery using JQuery.
The basic idea is that all image files are called x.png (where x is a number), and the program adds a number to the current number creating x+1.png and so on.
The code i have is:
function gal2(){
var amount = $(".imagelist > img").length;
var next = $("#display").attr('src').replace('.png', '');
if ($("#display").attr('src').replace('.png', '') >= amount) {
$("#display").attr('src', next+".png");
next++;
} else {
$("#display").attr('src', next+".png");
next++;
};
}
gal2 is called on a button press <input type="button" onclick="gal2()">,
.imagelist is a div containing the images,
#display is the main image being shown,
Example Website
The problem is that nothing happens except if one is selected than it will back to the original one every time.
P.S: It's for a year 9 secondary school project
You made some edits to your script and now it work fine : https://jsfiddle.net/IA7medd/qwmt7Lep/2/
function gal2(){
var amount = $(".imagelist > img").length;
var current = parseInt($("#display").attr('src').replace('.png', ''));
var next = current + 1;
if (current < amount) {
$("#display").attr('src', next+".png");
} else {
$("#display").attr('src', "1.png");
};
}
I have been looking around and I cannot seem to figure out how to do this, although it seems like it would be very simple.(mobile development)
What I am trying to do is display a message (kind of like an alert, but not an alert, more like a dialog) while a calculation is being made. Simply like a Loading please wait. I want the message to appear and stay there while the calculation is being done and then be removed. I just cannot seem to find a proper way of doing this.
The submit button is pressed and first checks to make sure all the forms are filled out then it should show the message, it does the calculation, then hides the message.
Here is the Calculation function.
function scpdResults(form) {
//call all of the "choice" functions here
//otherwise, when the page is refreshed, the pulldown might not match the variable
//this shouldn't be a problem, but this is the defensive way to code it
choiceVoltage(form);
choiceMotorRatingVal(form);
getMotorRatingType();
getProduct();
getConnection();
getDisconnect();
getDisclaimer();
getMotorType();
//restore these fields to their default values every time submit is clicked
//this puts the results table into a known state
//it is also used in error checking in the populateResults function
document.getElementById('results').innerHTML = "Results:";
document.getElementById('fuse_cb_sel').innerHTML = "Fuse/CB 1:";
document.getElementById('fuse_cb_sel_2').innerHTML = "Fuse/CB 2:";
document.getElementById('fuse_cb_result').innerHTML = "(result1)";
document.getElementById('fuse_cb_res_2').innerHTML = "(result2)";
document.getElementById('sccr_2').innerHTML = "<b>Fault Rating:</b>";
document.getElementById('sccr_result').innerHTML = "(result)";
document.getElementById('sccr_result_2').innerHTML = "(result)";
document.getElementById('contactor_result').innerHTML = "(result)";
document.getElementById('controller_result').innerHTML = "(result)";
//Make sure something has been selected for each variable
if (product === "Choose an Option." || product === "") {
alert("You must select a value for every field. Select a Value for Product");
**************BLAH************
} else {
//valid entries, so jump to results table
document.location.href = '#results_a';
******This is where the message should start being displayed***********
document.getElementById('motor_result').innerHTML = motorRatingVal + " " + motorRatingType;
document.getElementById('voltage_res_2').innerHTML = voltage + " V";
document.getElementById('product_res_2').innerHTML = product;
document.getElementById('connection_res_2').innerHTML = connection;
document.getElementById('disconnect_res_2').innerHTML = disconnect;
if (BLAH) {
}
else {
}
populateResults();
document.getElementById('CalculatedResults').style.display = "block";
} //end massive else statement that ensures all fields have values
*****Close out of the Loading message********
} //scpd results
Thank you all for your time, it is greatly appreciated
It is a good idea to separate your display code from the calculation code. It should roughly look like this
displayDialog();
makeCalculation();
closeDialog();
If you are having trouble with any of those steps, please add it to your question.
Computers are fast. Really fast. Most modern computers can do several billion instructions per second. Therefore, I'm fairly certain you can rely on a a setTimeout function to fire around 1000ms to be sufficient to show a loading message.
if (product === "Choose an Option." || product === "") {
/* ... */
} else {
/* ... */
var loader = document.getElementById('loader');
loader.style.display = 'block';
window.setTimeout(function() {
loader.style.display = 'none';
document.getElementById('CalculatedResults').style.display = "block";
}, 1000);
}
<div id="loader" style="display: none;">Please wait while we calculate.</div>
You need to give the UI main thread a chance to render your message before starting your calculation.
This is often done like this:
showMessage();
setTimeout(function() {
doCalculation();
cleanUp()
}, 0);
Using the timer allows the code to fall through into the event loop, update the UI, and then start up the calculation.
You're already using a section to pop up a "results" page -- why not pop up a "calculating" page?
Really, there are 4,000,000 different ways of tackling this problem, but why not try writing a "displayCalculatingMessage" function and a "removeCalculatingMessage" function, if you don't want to get all object-oriented on such a simple thing.
function displayCalculatingMessage () {
var submit_button = getSubmitButton();
submit_button.disabled = true;
// optionally get all inputs and disable those, as well
// now, you can either do something like pop up another hidden div,
// that has the loading message in it...
// or you could do something like:
var loading_span = document.createElement("span");
loading_span.id = "loading-message";
loading_span.innerText = "working...";
submit_button.parentElement.replaceChild(loading_span, submit_button);
}
function removeCalculatingMessage () {
var submit_button = getSubmitButton(),
loading_span = document.getElementById("loading-message");
submit_button.disabled = false;
loading_span.parentElement.replaceChild(submit_button, loading_span);
// and then reenable any other disabled elements, et cetera.
// then bring up your results div...
// ...or bring up your results div and do this after
}
There are a billion ways of accomplishing this, it all comes down to how you want it to appear to the user -- WHAT you want to have happen.
I want to calculate the time between two clicks of an attribute with javascript but I don't know how.
For example;
click here
if the user clicks more than once -let's say in 5 seconds- I want to display an alert. I'm using jQuery if that helps. I don't know much about javascript but I've been coding a small project in my free time.
Something like this would do the trick. Keep a variable with the time of the last click and then compare it when the user clicks the link again. If the difference is < 5 seconds show the alert
<a id='testLink' href="#">click here</a>
<script type='text/javascript'>
var lastClick = 0;
$("#testLink").click(function() {
var d = new Date();
var t = d.getTime();
if(t - lastClick < 5000) {
alert("LESS THAN 5 SECONDS!!!");
}
lastClick = t;
});
</script>
The following may help you getting started:
var lastClicked = 0;
function onClickCheck() {
var timeNow = (new Date()).getTime();
if (timeNow > (lastClicked + 5000)) {
// Execute the link action
}
else {
alert('Please wait at least 5 seconds between clicks!');
}
lastClicked = timeNow;
}
HTML:
click here
Create a variable to hold the time of a click, say lastClick.
Set up a click handler for the element you want to track clicks on.
Inside the handler, check for a value in lastClick. If there is no value, set it to the current time. If there is a value, compare it against the current time. If the difference is within the range you're checking for, display the alert.
Start with
var lastClicked = (new Date()).getTime(); //not zero