When reached amount get forwarded to an other html - javascript

So I have a scoreboard for a game I am making, if you press a button you get one point, this is the scoreboard. But I want to have it so that if you reach 10 points, you are taken to an other html, a victory screen.
This is my JS + HTML
<script type="text/javascript">
var clicks1 = 0;
function updateClickCount1(){
document.getElementById("clickCount1").innerHTML = clicks1;
}
</script>
<button type="button" onclick='clicks1++;updateClickCount1()' id="push"> Score +1 </button>
<div id="clickCount1">0</div>
</div>

Check the value within the function and redirect if it reached 10.
<script type="text/javascript">
var clicks1 = 0;
function updateClickCount1(){
document.getElementById("clickCount1").innerHTML = clicks1;
if(clicks1 == 10)
window.location = 'newpahe.html';
}
</script>

<script>
var clicks1 = 0;
function updateClickCount1(){
document.getElementById("clickCount1").innerHTML = ++clicks1;
if(clicks1>9) window.location.href="victory.html";
}
</script>
you can do like this set your counter as 0, increment it after user reach the score greater than 9 redirect to the victory page

Inside your update function, check if the number of clicks is greater or equal than 10. if it is the case use window.location to redirect
var clicks1 = 0;
function updateClickCount1() {
document.getElementById("clickCount1").innerHTML = ++clicks1;
if(clicks1 >= 10)
window.location = "victory.html";
}
<button type="button" onclick='updateClickCount1()' id="push">Score +1</button>
<div id="clickCount1">0</div>

Related

Assigning a function to an array of javascript buttons

When I click on of these button I want an item in sessionStorage to be assigned to true which is indicative of the button which was pressed. When the fourth button is clicked I was it to show what information was selected to know more about.
Right now my button aren't returning anything and I can't figure out how to loop through this and assign a function to every button
//simple html to print four buttons.
<!DOCTYPE html>
<html>
<head>
<title>Green Things</title>
<script type="text/javascript" src="example.js"></script>
</head>
<body>
<div><button id="moreAboutGrass" type="button" class="button">Send me more information about Grass</button></div>
<div><button id="moreAboutMolluscs" type="button" class="button">Send me more information about Green Molluscs</button></div>
<div><button id="moreAboutSweaters" type="button" class="button">Send me more information about Green Sweaters</button></div>
<div> <button id="infoChosen" type="button" class="button">Things you want more information about </button></div>
<div><output id = "output"></output></div>
</body>
</html>
window.onload = function() {
//getting an array of all the buttons
var y = document.getElementsByClassName("button");
//looping through all the buttons
for(count = 0; count < y.length; count++){
//Assigning an operation to the button
document.getElementById(y[count].id).onclick = function(count) {
//Assigning a variable to be the id name of button passed into this function
z = y[arguments[i]].id;
//If the button is the fourth button
if ( z == "infoChosen" ){
//Add in the things which were selected
document.getElementById("output").innerHTML = "";
if (sessionStorage["moreAboutMolluscs"] == "true"){
document.getElementById("output").innerHTML += "Green Molluscs\n";
}
if (sessionStorage["moreAboutSweaters"] == "true"){
document.getElementById("output").innerHTML += "Green Sweaters\n";
}
if (sessionStorage["moreAboutGrass"] == "true"){
document.getElementById("output").innerHTML += "Grass\n";
}
}else{
//if the button was on of the first 3 just set a variable to true so it can be printed later
sessionStorage.setItem(z, "true");
}
}
}
If the first button and then the fourth button is clicked the output should be
Green Molluscs
If the first and third button are clicked and then the fourth the output should be
Green Molluscs Green Sweaters
I need to do it in a loop
Try this
<!DOCTYPE html>
<html>
<head>
<title>Green Things</title>
<script type="text/javascript">
window.onload = function() {
//getting an array of all the buttons
var y = document.getElementsByClassName("button");
//looping through all the buttons
for(count = 0; count < y.length; count++){
//Assigning an operation to the button
var aa = y[count].id;
document.getElementById(y[count].id).onclick = function(aa) {
var z = aa.currentTarget["id"];
if ( z == "infoChosen" ){
document.getElementById("output").innerHTML = "";
if (sessionStorage["moreAboutMolluscs"] == "true"){
document.getElementById("output").innerHTML += "Green Molluscs\n";
}
if (sessionStorage["moreAboutSweaters"] == "true"){
document.getElementById("output").innerHTML += "Green Sweaters\n";
}
if (sessionStorage["moreAboutGrass"] == "true"){
document.getElementById("output").innerHTML += "Grass\n";
}
}else{
//if the button was on of the first 3 just set a variable to true so it can be printed later
sessionStorage.setItem(z, "true");
}
}
}
}
</script>
</head>
<body>
<div><button id="moreAboutGrass" type="button" class="button">Send me more information about Grass</button></div>
<div><button id="moreAboutMolluscs" type="button" class="button">Send me more information about Green Molluscs</button></div>
<div><button id="moreAboutSweaters" type="button" class="button">Send me more information about Green Sweaters</button></div>
<div> <button id="infoChosen" type="button" class="button">Things you want more information about </button></div>
<div><output id = "output"></output></div>
</body>
</html>
I would do it differently in this situation.
In my eyes the best option is to make a function for each button like this <button onclick="myFunction()">Click me</button>and that function changes a variable too true or false. And when you click the 4th button it might be the best too use the switch statement for each possibility for the right output.
I am not that experienced in coding yet so this might not be the most efficient way but I hope this helped you.
Well, firstly, you're not accessing your sessionStorage correctly. See this. And what you're doing looks a bit like a mess. I've tidied up the code in my answer below so I'll just make some explanations here.
I decided to grab all your buttons using document.getElementsByTagName("button"); it may not always be applicable, but it feels suitable in your case.
I've changed using a for loop using length, to just using the of operator. It basically iterates through an array without needing to length it.
I think the other parts concerning putting stuff into the sessionStorage is pretty straight forward, but if you are unsure, just ask me and I'll rewrite it.
jsfiddle: https://jsfiddle.net/ryvcvp42/

Alert Message Button

Trying to get the button called, "check" to show the var result from the answer prompt1 function. For whatever reason when I run the code nothing happens when the button is clicked. I know the calculation is right because, when I set the answer button to give the intended alert, it works properly. How do I get the second button to display my results entered?
<!DOCTYPE html>
<head>
<!--
Name: Dakota Trumbull
Date:
Class:
Purpose:
-->
<title>Math Test</title>
</head>
<body>
<h1>Simple Math Test</h1>
<p>Q1: 5 + 9 = ??</p>
<button id = "Q1A" onclick = "answerPrompt1()">Answer</button>
<button id = "Q1C" onclick ="showResult()">Check</button>
<p></p>
<p>Q2: 4 * 6 = ??</p>
<button id = "Q2A">Answer</button>
<button id = "Q2C">Check</button>
<p></p>
<p>Q3: 25 - 14 = ??</p>
<button id = "Q3A">Answer</button>
<button id = "Q3C">Check</button>
<p></p>
<p>Q4: 48 / 3 = ??</p>
<button id = "Q4A">Answer</button>
<button id = "Q4C">Check</button>
<p></p>
<p>Q5: 26 % 6 = ??</p>
<button id = "Q5A">Answer</button>
<button id = "Q5C">Check</button>
</body>
<script>
//Q1
function answerPrompt1()
{
var answer1 = prompt("Enter your answer: ");
var convertedNum1 = parseInt(answer1, 10);
var result = (convertedNum1 == 14)? "You're right!" :
"Sorry, that's incorrect.";
}
function showResult()
{
alert(result);
}
</script>
</html>
result is declared in answerPrompt1, which gives it local scope (i.e. it isn't visible outside that function). move the declaration to just before the function:
var result = "You have not given an answer yet";
function answerPrompt1()
{
var answer1 = prompt("Enter your answer: ");
var convertedNum1 = parseInt(answer1, 10);
result = (convertedNum1 == 14)? "You're right!" :
"Sorry, that's incorrect.";
}
function showResult()
{
alert(result);
}
<body>
<h1>Simple Math Test</h1>
<p>Q1: 5 + 9 = ??</p>
<button id = "Q1A" onclick = "answerPrompt1()">Answer</button>
<button id = "Q1C" onclick ="showResult()">Check</button>
</p>
</body>
You should change your result variable in a way that it can be accessible to both functions answerPrompt1() and showResult() You can have a clear understanding about how javascript scope works from here.
var result = "You have not given an answer yet"; //this variable is accessible to both functions
function answerPrompt1()
{
var answer1 = prompt("Enter your answer: "); //this variable only accessible inside the function answerPrompt1()
var convertedNum1 = parseInt(answer1, 10);
result = (convertedNum1 == 14)? "You're right!" :
"Sorry, that's incorrect.";
}
function showResult()
{
alert(result);
}

We are analysing some code, I get what it is doing, but there is a line of code which I don't understand

This is the full code:
<html>
<head>
<script type='text/javascript'>
var banners = ["Red.jpg","Amber.jpg","Green.jpg"];
var bnrCntr = 0;
var timer;
function banCycle()
{
if(++bnrCntr == 3)
bnrCntr = 0;
document.images.banner.src = banners[bnrCntr];
timer = setTimeout("banCycle()",1000);
}
function stopCycle()
{
clearTimeout(timer);
}
</script>
</head>
<body>
<img src="Red.jpg" name="banner" width=110 height=200>
<form>
<input type="button" value="Cycle" name="Cycle" onclick="banCycle()">
<input type="button" value="Stop" name="Stop" onclick="stopCycle()">
</form>
</body>
</html>
It is the line that I don't understand:
if(++bnrCntr == 3)
Can anyone tell me what this line does?
The line
if (++bnrCntr == 3)
does the same thing as
if ((bnrCntr += 1) == 3)
or
bnrCntr = bnrCntr + 1;
if (bnrCntr == 3)
The value of bnrCntr is incremented, and the result is then assigned back to the variable. Then the value is compared to 3. The ++ operator is called the prefix increment operator.
It first increases the bnrCntr value by 1 and if that value equals to 3 it's set back to 0. You get circular banner changing this way. You could also write it this way, so it's more understandable:
if (++bnrCntr == banners.length)
bnrCntr = 0;
So, when the index goes out of the bounds of the array, start from the beginning.

Display click count and redirect to a url

I have found the below code to check the count of times the button has been clicked. However, I would like the button to redirect to an URL once it is clicked and update the click count.
<html>
<head>
<title>Increment count when button is clicked</title>
</head>
<body>
<input type="button" value="Count" id="countButton" />
<p>The button was pressed <span id="displayCount">0</span> times.</p>
<script type="text/javascript">
var count = 0;
var button = document.getElementById("countButton");
var display = document.getElementById("displayCount");
button.onclick = function(){
count++;
display.innerHTML = count;
}
</script>
</body>
</html>
button.onclick = function(){
count++;
display.innerHTML = count;
window.location = "http://jonathanmh.com";
}
This would do the trick, but nobody would ever see the number, because it simply goes away, after the user is redirected to another page. If you want to save the number for other users to see, you need to save it on the server and preferably in a database.
To achieve that you need to store click count in cookie or localStorage (or anywhere else where your data persists):
var button = document.getElementById("countButton");
var display = document.getElementById("displayCount");
button.onclick = function(){
if (isNaN(localStorage.yourCounter))
localStorage.yourCounter = 0;
localStorage.yourCounter++;
display.innerHTML = localStorage.yourCounter;
window.location = 'http://jsfiddle.net/'
}

Javascript: Uncaught TypeError: Cannot set property 'innerHTML' of null

I've browsed through a couple of questions but I couldn't find any help.
By the way this is the first time I'm asking a question here so I might not do it the right way. Anyway, the following line is causing me the problem
/* cursorPps defined above */
document.getElementById("cursorPps").innerHTML = cursorPps;
The cursorPps variable is already defined. Can someone point out what other possible stuff could have caused this error?
Edit: By the way the problem is that it is not updating the value on HTML, although the value of the variable changes.
HTML:
<html>
<head>
<title>Potato Clicker</title>
<link rel="stylesheet" type="text/css" href="interface.css">
</head>
<body>
<div id="left">
<img id="potato-img" onClick="potatoClick(clickPower)" src="stockvault-potatoes107220.jpg" width="300" height="300">
<br>
<div id="mainDisplay">
<span id="potatoes">0</span> <br> potatoes
<br>
<br>
Producing <span id="pps">0</span> potatoes per second
<br>
</div>
Cursors: <span id="cursors">0</span>
</div>
<div id="middle">
<div id="buildings" onClick="buyCursor()"> Buy Cursor </div>
</div>
<script src="main.js"></script>
</body>
</html>
Javascript:
//variables
var potatoes = 0; //potatoes
var clickPower = 1; //potatoes gained per click
var pps = 0; //potatoes per second
var cursors = 0; //cursors
var cursorCost; //cost of cursor
var cursorPps = 0; //total cursor potatoes per second
var cursorBuy; //cursor buy button
//functions
function potatoClick(number) {
potatoes = potatoes + number;
document.getElementById("potatoes").innerHTML = potatoes;
}
function buyCursor() {
var cursorCost = Math.floor(10 * Math.pow(1.2,cursors));
if (potatoes >= cursorCost) {
pps = pps - cursorPps;
cursors = cursors + 1;
potatoes = potatoes - cursorCost;
cursorPps = cursorPps + 1;
pps = pps + cursorPps;
document.getElementById("potatoes").innerHTML = potatoes;
document.getElementById("cursors").innerHTML = cursors;
document.getElementById("cursorPps").innerHTML = cursorPps;
document.getElementById("pps").innerHTML = pps;
}
else {
alert("Not enough potatoes!")
}
var nextCost = Math.floor(100 * Math.pow(1.2,cursors));
document.getElementById('cursorCost').innerHTML = nextCost;
}
window.setInterval(function () {
if (pps > 0) {
potatoClick(pps);
}
}, 1000);
Make sure that
You have an element has that ID
The element IS on the page before that Javascript is run
You bind the execution of your JS to an event (follow-up from previous) that happens after the element is on the page
The cursorPps variable has been populated
Here's a simple codepen that demonstrates a way to do it http://codepen.io/leopic/pen/wDtIB
<div id="myDiv"></div>
You have an element with that ID
var length = document.querySelectorAll('#myDiv').length;
if(length > 0) {
// This element exists in the DOM tree
}
You bind the execution of your JS to an event (follow-up from previous) that happens after the element is on the page
<body>
<div id="myDiv"></div>
<script>
var length = document.querySelectorAll('#myDiv').length;
console.log(length);
</script>
</body>
The cursorPps variable has been populated
if(cursorPps != undefined)

Categories

Resources