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>
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 apologize I am new to javascript. I am trying to toggle a relay from a website using setInterval. The relay is a Sainsmart with 16 channels and it is connected to an arduino controlled by a raspberry pi. The goal is to eventually have three independent relays toggling at particular intervals. However, every attempt to get the first one working fails. In addition, every time I add a setInterval within a function or global, freezes the live streaming video from my ip camera. I am using a sandbox key through ably.
The html code and script work to toggle the relay on, and then a second button will toggle it off, but I need a single button to accomplish it.
The button initiates the sequence with a counter dictating whether the relay toggles on or off. It is set up to toggle on with an even number and off with an odd number. Any help would be greatly appreciated.
Here is the updated code I am trying to work with.
<div class="grid-item"><button id="37" onclick="startOnOff()">Start</button>
</div>
<script src="http://cdn.ably.io/lib/ably.min-1.js"></script>
<script>
var count = 0;
function startOnOff() {
var on = "37" + "on";
var off = "37" + "off";
if (counter % 2 == 0) {
toggleRelay(on);
count += 1;
} else if (count % 2 == 1) {
toggleRelay(off);
}
setInterval(startOnOff, 2000);
}
You have count in a few places and counter in one place where it should be count.
Assuming toggleRelay() is defined somewhere else in your code, try this:
var count = 0;
var on = "37" + "on";
var off = "37" + "off";
function startOnOff() {
if (count % 2 == 0) {
toggleRelay(on);
} else {
toggleRelay(off);
}
count += 1;
setTimeout(startOnOff, 2000);
}
count += 1; should be outside of the if conditional statement,
and use setTimeout() when calling startOnOff() recursively.
Very much a newbie here and wanting a bit of guidance.
I'm trying to create a project where you bind a key to start a timer then show an output in the results box. However i'm facing an issue where I need to create a new line if the user releases the bound button to start a new timer, however I can't find a way to start the timer again. Bear in mind within the time, a user could press the bound key over a hundred times, I don't want to manually create new lines and timer's.
My thoughts are creating a a random token, then on release, it creates a break, if the next line doesn't match this token it begins again.
Edit:So you can see, the value is based on the 2 variables, and even when I hold down the specific button again, it just adds to the current smallTime. I know this is how it's currently build, but i'm trying to get it to reset and go to the next line dynamically.
Any help would be greatly appreciated.
<html>
<head>
<textarea class="code_input" name="allInputs" id="textareaCode" wrap="logical" rows="10" cols="50" readonly="true"> </textarea>
<script type="text/javascript">
var shortSeconds = 0;
var shortmillisec = 0;
function buttonPressed(e) {
key = String.fromCharCode(e.keyCode).toLocaleLowerCase()
//alert (key)
keyInput = e.keyCode
if (withinTime == true && key == bind) {
shortDisplay()
shortTimerFunction();
}
}
function shortDisplay() {
if (shortmillisec >= 9) {
shortmillisec = 0
shortSeconds += 1
}
else
shortmillisec += 1
}
function startstoptimerShort() {
if (shortTimer > 0) {
clearTimeout(shortTimer);
shortTimer = 0;
} else {
withinTime = true
shortTimerFunction()
}
}
function shortTimerFunction() {
smallTime = shortSeconds + "." + shortmillisec;
shortTimer = setTimeout("shortTimerFunction()", 100);
//need to work out what line to put the output on
allInputs = document.getElementById('textareaCode')
allInputs.value = (textbox3.value) + (": " + smallTime) + '\n';
}
</script>
</body>
</html>
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.
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.