EDIT: thanks to all of you it has been fixed (: thank you soooooooo much
I cant get the alert,confirm or prompt to work, here is my code (not the full code but the beginning is the part tht I cant get to work so im leaving that and omitting the end of the code, so here it is :
var warGood = 0
var warEvil = 0
var life
var mh = false
var document.Gold = 1000;
var gems = 1000;
var lb = false
var Stellar_grenades = 0
var Cosmic_grenades = 0;
var Level = 1
var person
person = prompt("please enter your name", "Specimen")
if (person != null) {
if (person == "shit") {
alert("Really? choose a new MORE APPROPRIATE name", "Ok ill choose a new More APPROPRIATE name")
}
else if (person != "shit"){
if (person != null) {alert(
"welcome " + person + " to the universe")
}
}
alert(
"not too long ago your planet was blown up in the midst of a universal war, you luckily survived and fled to another planet");
alert("You are now here, On Planet Vecron, Here you will build up your base,")
alert("then you can eventually go on missions to distant planets,")
alert("Upon Reaching the final mission, you will notice one thing")
alert ("Your Not on a new planet, but rather a new universe,")
alert("this universe holds the Key to cosmic peace,")
alert(" This Key is the Community Pendant")
life = confirm("Do you have what it takes to get this pendant and end the universal war?")
if (life == true) {
alert("Thank you " + person + "You will make a fine adventurer");
alert("gold is the main currency Here on vecron")
alert(" If you want anything it can buy it, with a few exceptions")
alert("You cant buy the Community Pendant")
alert(" Or gems Or the special 12 summoners tools")
alert(" Shh the summoners tools will be talked about later")
alert("saving your game is important,")
alert("To Open the shop Press S")
alert("To Save Press F")
alert("To get money you simply have to press the money button!")
alert("The Ding Is to make sure you actually have good reflexes while in missions.")
alert("You get missions after you unlock the mission hall")
alert("then you can start the first journey on your many adventures")
document.write("you have " + document.Gold + " Gold and " + gems + " gems")
alert("Go Get that Pendant and save the world")
<img src = "logo.png" alt = "logo">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
I really cant figure it out, it was working fine a few weeks ago, then I took a break and came back to it and all of a sudden it wouldn't work anymore
Document.gold isn't valid JS. If you want global variables you can just use the var keyword. This will add them to the global scope. Like this:
var gold = 1000;
Document the main object of the DOM API. The HTML document is parsed and loaded into memory in a JS representation. You then can modify the DOM which will cause the UI to update. You are already doing this in the following code (changed it a bit):
var gold = 1000;
var gems = 25;
document.write("you have " + gold + " Gold and " + gems + " gems")
Related
I am trying to write a web page where I can detect button presses on a Xbox controller and show a user a boolean value based on the button pressed. Right now, I can detect a controller being connected and show that as a string. The documentation says to use this code to detect a button press here:
var isPressed = navigator.getGamepads()[0].pressed;
but Chrome shows this error when using it:
Uncaught TypeError: Cannot read property 'pressed' of null
The error is linked to the .pressed part of the above line of code. All the documentation is on the Mozilla site, so I'm assuming they used FireFox when writing the tutorials.
What I ideally want to end up with is this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<h id="button"></h>
<h id="gpInfo"></h>
<script>
var i = 1;
window.addEventListener("gamepadconnected", function(e) {
var gp = navigator.getGamepads()[e.gamepad.index];
document.getElementById("gpInfo").innerHTML = ("A " + gp.id + " was successfully detected! There are a total of " + gp.buttons.length + " buttons.")
//alert("A " + gp.id + " was successfully detected!")
});
var isPressed = navigator.getGamepads()[0].pressed;
document.getElementById("button").innerHTML = isPressed;
</script>
<!-- <script type="text/javascript" src="gamepadtest.js"></script> -->
</head>
</html>
The code would print a boolean value on the screen for users to see when they press a button.
This is my first time working with JavaScript and HTML. If you could make your answer noob-friendly that would be great! Documentation for Gamepad API and for GamepadButton
You shouldn't reference the Gamepad object until the gamepadconnected event has been thrown. Also, you'll need a loop to poll the button value. Here's some revised code:
var i = 1;
window.addEventListener("gamepadconnected", function(e) {
var gp = navigator.getGamepads()[e.gamepad.index];
document.getElementById("gpInfo").innerHTML = ("A " + gp.id + " was successfully detected! There are a total of " + gp.buttons.length + " buttons.")
//alert("A " + gp.id + " was successfully detected!")
setInterval(function(){
isPressed = gp.buttons[0].pressed;
document.getElementById("button").innerHTML = isPressed;
}, 100)
});
I don't have enough reputation to just add a comment to Caleb Denio's answer, but regarding Nathan's comment on that answer:
I have used your example to listen for 20 buttons and i can detect each button, but once i have pressed one, it will not change another result for a different button.
I see the same behaviour on Chrome 90. Specifically, a new GamepadList instance, containing new Gamepad instances, all seem to be created each time the state of any gamepad changes (e.g. which of its buttons are pressed).
You can test it with this:
var gamepads = null;
function callback() {
var new_gamepads = navigator.getGamepads();
if(new_gamepads !== gamepads) {
console.log('New GamepadList!', new_gamepads);
gamepads = new_gamepads;
}
}
var interval = setInterval(callback, 100);
...for me, that logs 'New GamepadList!' each time I press/release a button.
Long story short, you need to poll navigator.getGamepads() each frame in order to detect changes in gamepad state.
A minimalist fix for Caleb Denio's answer would therefore be:
var i = 1;
window.addEventListener("gamepadconnected", function(e) {
var gp = navigator.getGamepads()[e.gamepad.index];
document.getElementById("gpInfo").innerHTML = ("A " + gp.id + " was successfully detected! There are a total of " + gp.buttons.length + " buttons.")
//alert("A " + gp.id + " was successfully detected!")
setInterval(function(){
// ===> Get a fresh GamepadList! <===
var gp = navigator.getGamepads()[e.gamepad.index];
isPressed = gp.buttons[0].pressed;
document.getElementById("button").innerHTML = isPressed;
}, 100)
});
I am a noob here in JS and I am doing my homework making a simple color guessing game. So far everything works as far as the criteria goes.
My only problem is that I can't figure out how to make it so that the background changes instantly upon user input (Right after clicking [OK] at the Prompt). As of now with the code below, the background changes only after clicking [OK] in the Congrats alert..I am pretty sure it's possible because my prof showed in the lecture an example he did where the background color changed right after guessing the correct color!
Also, it would be nice if any pros out there could give me suggestions on polishing my code. I have a feeling that it is messy and too complex than what its trying to achieve..Heh..
PS: I know that js logic should be separated in the page but my prof insisted we do this exercise with the script inline!
Thank you!
<body onload="doGame()">
<script>
var myBody = document.getElementsByTagName("body")[0];
var target;
var answer;
var guessInputText;
var guessInput;
var finished = false;
var guessAmount = 0;
var colors = ['Salmon', 'Tomato', 'Moccasin', 'Peru', 'Olive', 'Teal', 'Navy', 'Thistle', 'Beige', 'Gray'];
var colorsSorted = colors.sort();
var colorsSortedString = colors.join(', ');
function doGame() {
var randomColorNum = Math.random() * 10;
var randomColorNumInt = Math.floor(randomColorNum);
target = colors[randomColorNumInt + 1];
answer = target.charAt(0).toLowerCase() + target.slice(1).toLowerCase(); //makes sure answer is in lowercase
alert("The answer is " + target + " or " + answer); //for debugging
while(!finished) {
guessInputText = prompt('I am thinking of one of these colors:\n\n' +
colorsSortedString + '\n\n' +
'What color am I thinking of?');
guessInput = guessInputText.charAt(0).toLowerCase() + guessInputText.slice(1).toLowerCase(); //converts whatever input into lowercase
guessAmount += 1;
finished = checkGuess(); //checks to see if user input is correct
}
}
function checkGuess() {
if ((colors.indexOf(guessInputText.charAt(0).toUpperCase() + guessInputText.slice(1).toLowerCase()) > -1) == false) {
alert("Sorry, I don't recognize your color.\n\n" +
"Please try again!");
return false;
}
if (guessInput > answer) {
alert("Sorry, Your guess is incorrect!\n\n" +
"Hint: Your color is alphabetically higher than mine.\n\n" +
"Please try again!");
return false;
}
if (guessInput < answer) {
alert("Sorry, Your guess is incorrect!\n\n" +
"Hint: Your color is alphabetically lower than mine.\n\n" +
"Please try again!");
return false;
}
myBody.style.background = answer;
alert("Congratulations! You have guessed the color!\n\n" +
"It took you " + guessAmount + " guesses to finish the game!\n\n" +
"You can see the color in the background.");
return true;
}
</script>
</body>
If you want to modify the background before the [OK] on congrats prints, you just have to move this line
myBody.style.background = answer;
But.. Testing your snippet, the background change right after I press OK on the guess color prompt.
So what do you want exactly ? Can you give us an example step by step ?
I have following code to implement simple practice shopping cart using JavaScript. There is a checkout link which calls getcookie() to check the value of the cookies stored. When nothing is in the cookie then click on the link alerts to make input. If non of the values are entered in the input box and hit "add to cart" then validation is done and error message is alerted.
For some reason, the cookie is not taking the value from the input field. I tried quite a while now but was not able to debug the code. Just an empty alert box is shown at last. I appreciate any debugging. Thanks in advance.
<script type="text/javascript">
var value;
var productID;
function setItem(abd) {
value = abd.value;
productID = abd.getAttribute("productID");
var intRegex = /^\d+$/;
var numberOfItems;
if (!intRegex.test(value) || (value <= 0)) {
alert('Please Enter valid numberofitem');
} else {
numberOfItems = value;
}
}
function getCookie() {
if (value == undefined) {
alert("There is nothing in the shopping cart!");
} else {
var cookieArray = document.cookie.split(';');
var printHolder = "";
for (var i = 0; i < cookieArray.length; ++i) {
var pairArray = cookieArray[i].split('=');
alert(pairArray[0]);
}
alert(printHolder);
}
}
function setCookie() {
if (value == undefined) {
alert("Please add number of items in text box");
} else {
document.cookie = productID + "=" + value + "; ";
alert(value + " Product(s) with id " + productID +
" has been added to shopping cart!");
}
}
</script>
Checkout
<input name="item-select" id="item-select"
productid="p001" style="width: 50px" onBlur="setItem(this)" >
<button type="button" onclick="setCookie()">Add to cart.</button>
The result I wanted is something like this at last!
This code works perfectly fine with some changes.
I was using chrome and later found out that
Google Chrome doesn't create cookies when the file is on the local machine and loaded in browser directly using file path.
Rather try with localhost. It is definitely working when you put the code in server. Chrome became pain in a b*t here!
If you were for idea on creating shopping cart with Javascript follow this link.
http://www.smashingmagazine.com/2014/02/create-client-side-shopping-cart/
Your getCookie is likely to give you incorrect results.
var cookiearray= document.cookie.split(';');
var toprint="";
for(var i=0; i<cookiearray.length; ++i)
{
var pairArray= cookiearray[i].split('=');
alert(pairArray[0]);
}
alert(toprint);
Two things wrong here;
1) When you are in your for loop, each time you loop you are alerting the first item in your array at all times pairArray[0] you need to change that to pairArray[i]
2) You are displayed with an empty alert because thats what you have assigned to the toprint variable.
- You assign toprint an empty string before your for loop, then you are alerting that variable without assigning it a new value, so you will be displayed with an empty alert box!
- Also make sure your cookie array is not empty.
Give that a try, enjoy coding :)
Kush
This code pops up asking for the users input, and multiplies it by 0.00000116414.
I want to change this into a text input field and calc button, then perhaps add the ability to copy to the clipboard. How might I do this?
<html>
<head>
<meta name="Recommended Share Difficulty Calculator" content="[Share Dicciculty Calculator]" />
<title>Recommended Share Difficulty</title>
<script type="text/javascript">
function MathThing()
{
input = prompt("Enter your max KH/s.", "");
if (input==null || input=="")
{
return false;
}
share = 0.00000116414 ;
total = input * share;
alert(input + " * " + share + " = " + total);
}
</script>
</head>
<body>
Calculate
</body>
</html>
In order to manipulate the contents of a users clipboard you will need to utilize Flash. There is a great helper library called ZeroClipboard. I've set up a basic demo (that uses your JavaScript) that uses this JavaScript:
var client = new ZeroClipboard(
$("#copy"), {
moviePath: "http://zeroclipboard.org/javascripts/zc/ZeroClipboard_1.3.2.swf"
});
client.on('dataRequested', function (client, args) {
client.setText((function () {
input = prompt("Enter your max KH/s.", "");
if (input == null || input == "") {
return;
}
share = 0.00000116414;
total = input * share;
alert('"'+input + " * " + share + " = " + total+'" copied to your clipboard');
return input + " * " + share + " = " + total;
})());
});
This code follows the examples provided in the Zero Clipboard, the odd thing is it doesn't seem to work 100% of the time. I do most of my work on computers that don't have Flash so I don't know if this reliability is part of the library or my computer. Good luck.
Copying cross-browser is tricky.
Here is some super-simple code showing an input + button use case:
var el = document.getElementById('input-id');
var sub = document.getElementById('submit-id');
var calc = function(e){
var q = el.value;
var share = 0.00000116414;
if (q.length > 0){
var res = q * share;
alert(res);
}
};
sub.addEventListener('click', calc);
Fiddle: http://jsfiddle.net/G6T76/3/
You'll probably want to do a bit more validation on the input, though.
I recently started learning javascrpt, but I have some experience with C#. My school gave me an old text book called Complete Concepts and Techniques(second Edition). this book was written by Shelly Cashman and Dorin Quasney... My problem is that I cant get any of the methods or functions to work. Here are 2 of my most current issues:
var scrollMsg = "Mortage rates are at their lowest!"
var msgSpace = "--- ---"
var beginPos = 0
function scrollingMsg() {
document.msgForm.scrollingMsg.value =
scrollMsg.substring(beginPos,scrollMsg.length)+msgSpace+scrollMsg.substring(0,begi
nPos)
beginPos = beginPos + 1
If (beginPos > scrollMsg.length) {
beginPos = 0
}
window.setTimeout("scrollingMsg()",200)
}
function doMort() {
document.MortCalc.Amount.value=" "
document.MortCalc.Rate.value=" "
document.MortCalc.Years.value=" "
document.MortCalc.Payment.value" "
document.MortCalc.Amount.focus()
}
The scrollingMsg() function does not work. It does not place anything in the scrollingMsg text box. So there is no message in it. My second issue is with the doMort() function. The function does clear any of the boxes nor does it set a focus. Can you please tell me what's wrong. P.S. These are not my own code. These were project codes from the txt book, but they do not work.
Try adding semicolons after each statement, and you have a typo ('If' needs to be lowercase).
I fixed the code to comply with JSLint, use this site to verify your javascript
http://www.javascriptlint.com/online_lint.php
var scrollMsg = "Mortage rates are at their lowest!";
var msgSpace = "--- ---";
var beginPos = 0;
function scrollingMsg() {
document.msgForm.scrollingMsg.value = scrollMsg.substring(beginPos,scrollMsg.length) + msgSpace + scrollMsg.substring(0,beginPos);
beginPos = beginPos + 1;
if (beginPos > scrollMsg.length) {
beginPos = 0;
}
window.setTimeout("scrollingMsg()",200);
}
function doMort() {
document.MortCalc.Amount.value=" ";
document.MortCalc.Rate.value=" ";
document.MortCalc.Years.value=" ";
document.MortCalc.Payment.value=" ";
document.MortCalc.Amount.focus();
}