JavaScript updating a global variable - javascript

I am currently not the most experienced in Javascript and I'm trying to learn bit by bit. Anyway... how do I update the balance variable more efficiently?
Currently I believe I am doing this wrong. Also my button does not work on click event.
Anything would be a massive help! Thank you.
// Set global variables
var name;
var balance;
var weed;
// Ask the user his name for his character
name = window.prompt("What is your name?", "Cap'n Grow");
var finalName = document.getElementById('name');
finalName.textContent = name;
// Set the balance to default
balance = 100;
var FinalBalance = document.getElementById('balance');
FinalBalance.textContent = balance;
// Set the balance of weed to default
weed = 10;
var FinalWeed = document.getElementById('gear');
FinalWeed.textContent = weed;
// Sell function
function sellGear() {
var check = window.prompt("Are you sure you want to sell 5 bags?", "Yes");
if (check === 'Yes' && weed >= 5) {
console.log("Transaction was successful!");
// Update the balance
var updBalance = document.getElementById('balance');
updBalance.textContent = balance + 150;
} else {
console.log("Failed!")
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div id="container">
<header>
<div class="dashboard">
<div id="name"></div>
<div id="balance"></div>
<div id="gear"></div>
<div id="sell">
<button id="sellButton" onlick="sellGear()">Sell?</button>
</div>
</div>
</header>
</div>
</body>
<script src="js/global.js"></script>
</html>

Here is the solution and a suggestion:
Try to use java script code at the end of your HTML.
<html lang="en">
<head>
<title></title>
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div id="container">
<header>
<div class="dashboard">
<div id="name"></div>
<div id="balance"></div>
<div id="gear"></div>
<div id="sell">
<button id="sellButton" onclick="return sellGear();">Sell?</button>
</div>
</div>
</header>
</div>
</body>
<script src="js/global.js"></script>
</html>
<SCRIPT>
// Set global variables
var name;
var balance;
var weed;
// Ask the user his name for his character
var name = window.prompt("What is your name?", "Cap'n Grow");
var finalName = document.getElementById('name');
finalName.textContent = name;
// Set the balance to default
var balance = 100;
var FinalBalance = document.getElementById('balance');
FinalBalance.textContent = balance;
var weed = 10;
var FinalWeed = document.getElementById('gear');
FinalWeed.textContent = weed;
// Sell function
function sellGear() {
var check = window.prompt("Are you sure you want to sell 5 bags?", "Yes");
if (check === 'Yes' && weed >= 5) {
console.log("Transaction was successful!");
// Update the balance
var updBalance = document.getElementById('balance');
updBalance.textContent = balance + 150;
} else {
console.log("Failed!")
}
}
</SCRIPT>

Related

How to run JavaScript in WebStorm

I'm new at this so apologies in advance if I'm missing something obvious, but I'm not able to figure out how to run JavaScript in WebStorm. The WebStorm documentation says to simply open the HTML file in the browser, but that doesn't seem to work. For what it's worth, everything is working up on codepen.io.
Here's the HTML (for a simple weather app):
<body>
<head>
<script src="script.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="style.css">
</head>
<div class="container-fluid">
<div class="col-sm-3">
</div>
<div class="col-sm-6">
<div class="white-box text-center">
<span>Weather where you are:</span>
<div class="loc"></div>
<div class="weather"></div>
<div class="temp"></div>
<br>
</div>
</div>
<div class="col-sm-3">
</div>
</div>
</body>
And here's the script (still in draft, as it needs to be expanded to, among other things, link to images covering all values for 'weather'):
$(document).ready(function() {
$( window ).on("load", function(){
$.getJSON("http://ip-api.com/json", function(json) {
var json;
json = JSON.stringify(json);
var obj = JSON.parse(json);
var latitude = obj.lat;
var longitude = obj.lon;
$.getJSON("http://api.openweathermap.org/data/2.5/weather?lat="+latitude+"&lon="+longitude+"&appid=74a6725c2ca6f1342464bb9005bf0b63", function(json) {
var json;
json = JSON.stringify(json);
var obj = JSON.parse(json);
var loc = obj.name;
var weather = obj.weather[0].description;
var tempInCelsius = obj.main.temp - 273.15;
var tempInCelsiusString = tempInCelsius.toFixed(1) + " &#8451";
var tempInFahrenheit = obj.main.temp * 9/5 - 459.67;
var tempInFahrenheitString = tempInFahrenheit.toFixed(1) + " &#8457";
var tempStringCombined = tempInCelsiusString + " | " + tempInFahrenheitString;
$(".loc").html(loc);
if(weather === "haze"){
weather = "<img src='https://cdn3.iconfinder.com/data/icons/chubby-weather/440/fog-512.png'>";
}
$(".weather").html(weather);
$(".temp").html(tempStringCombined);
});
});
});
});
Many thanks in advance for any help!
Select the tab of html file(say index.html), and click in the menu Run > Run... and select index.html.

switch from image to random image onclick with JavaScript

I'm trying to build something that would resemble a slide show, where you have an image and when you click on it, it is replaced by another randomly in my series of images. I first tried with simple html, but of course the images don't switch randomly. So I did my research and found that it could be done with an array in Javascript. I just don't really know a lot about javascript…
This is what I could find but it doesn't work, I'm sure there is a stupid mistake in there that I can't see:
this is my javascript
function pickimg2() {
var imagenumber = 2 ;
var randomnumber = Math.random();
var rand1 = Math.round((imagenumber-1) * randomnumber) + 1;
myImages1 = new Array();
myImages1[1] = "img_01.gif";
myImages1[2] = "img_02.gif";
myImages1[3] = "img_03.gif";
myImages1[4] = "img_04.gif";
myImages1[5] = "img_05.gif";
myImages1[6] = "img_06.gif";
myImages1[7] = "img_07.gif";
myImages1[8] = "img_08.gif";
myImages1[9] = "img_09.gif";
var image = images[rand1];
document.randimg.src = "myImages1";
}
there is my html
<!DOCTYPE html>
<html>
<head>
<title>mur</title>
<link rel="stylesheet" href="style.css">
<link rel="JavaScript" href="script.js">
</head>
<body onLoad="pickimg2">
<div class="fenetre">
<img src="img_01.gif" name="randimg" border=0>
</div>
</body>
</html>
If someone has another solution I'm open to it!
Fix your script link like RamenChef mentioned:
<script type="text/javascript" src="script.js"></script>
Here's the updated code, check console.log to see the different image urls getting requested.
var myImages1 = new Array();
myImages1.push("img_01.gif");
myImages1.push("img_02.gif");
myImages1.push("img_03.gif");
myImages1.push("img_04.gif");
myImages1.push("img_05.gif");
myImages1.push("img_06.gif");
myImages1.push("img_07.gif");
myImages1.push("img_08.gif");
myImages1.push("img_09.gif");
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function pickimg2() {
document.randimg.src = myImages1[getRandomInt(0, myImages1.length - 1)];
}
<div class="fenetre">
<a href="#" onClick="pickimg2();return false;">
<img src="img_01.gif" name="randimg" border=0>
</a>
</div>
this code bellow is working. I hope it's what you were asking for
var images = [
"http://img1.science-et-vie.com/var/scienceetvie/storage/images/galerie/deepsea-challenge-le-film-de-james-cameron-livre-des-images-inedites-des-grands-fonds-marins-5165/19818-1-fre-FR/Deepsea-challenge-le-film-de-James-Cameron-livre-des-images-inedites-des-grands-fonds-marins_square500x500.jpg",
"http://static.mensup.fr/photos/145240/carre-premieres-images-officielles-pour-assassin-s-creed-rogue.jpg",
"http://www.pnas.org/site/misc/images/16-01910.500.jpg" ];
init();
function random_image(images) {
var random = randomize(images);
while(images[random] === document.getElementById("image").src){
random = randomize(images)
}
document.getElementById("image").src = images[random].toString();
}
function randomize(array){
return Math.floor((Math.random() * (array.length)));
}
function init() {
document.getElementById("image").addEventListener("click", function(){
random_image(images);
});
random_image(images);
}
<!DOCTYPE html>
<html>
<head>
<title>Bonjour</title>
</head>
<body >
<div class="fenetre">
<img id="image" src="" name="randimg" >
</div>
</body>
</html>

program does not recognize the number in the number input

I need your help :-)
Here's the code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Der Einmaleins - Trainer</title>
<link href = "style.css" type = "text/css" rel = "stylesheet">
<!--<script src = "script1m1.js"></script>-->
</head>
<body>
<h1>Der Einmaleins - Trainer</h1>
<button type="button" onclick = "start();">Start</button>
<!--<button type = "button" onclick = "fertig();">Fertig!</button>-->
<input id = "erginput" type = "number" >
<!--<label id = "rn1"></label>
<label id = "multiplication"></label>
<label id = "rn2"></label>
<br>-->
<label id = "feedback"></label>
</body>
<script>
function start(){
var ergebnis = document.getElementById("erginput").innerHTML;
document.getElementById("feedback").innerHTML = ergebnis;
}
</script>
</html>
The problem: When I set a number in the number input and click on start, the number is not shown.
Thanks in advance !
Ji W
input elements don't have innerHTML, they have value, so:
function start(){
var ergebnis = document.getElementById("erginput").value;
// Note -------------------------------------------^^^^^
document.getElementById("feedback").innerHTML = ergebnis;
}
(label elements do have innerHTML, which is why there's only one change above.)

Library.add is not a function error

I am trying to execute this code:
var addButton = document.querySelector("#add");
var searchButton = document.querySelector("#search");
var titleInput = document.querySelector("#title");
function Book(title) {
this.title = title;
}
function Library() {
this.books = [];
}
Library.prototype.add = function() {
this.add = function(book) {
this.books.push(book);
};
}
var library = new Library();
//Library UI
var libraryUI = {
//Add a new book
addBook: function() {
var listItem = libraryUI.createNewBook(titleInput.value);
Library.add(listItem);
console.log(Library.books);
},
//Create a new book
createNewBook: function(title) {
var book = new Book(title);
return book;
}
};
addButton.addEventListener("click", libraryUI.addBook);
The HTML is here:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Library App</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<h1>Personal Library</h1>
<label for="title">Title: </label>
<input type="text" id="title">
<button id="add">Add</button>
<button id="search">Search</button>
<p id="display"></p>
<script src="js/app.js"></script>
</body>
</html>
What I'm trying to do is press the addButton and the onclick will run the addBook function under the libraryUI object. The title of the book, in an input field, will then be used to create an object with the title of the book in it. I want to add that book to a list of books (an array) in an instance of Library. When I try to do so with the following code, I get the error "Uncaught TypeError: Library.add is not a function". I thought that Library.add is a function.
I added:
var library = new Library();
because I thought I had forgotten to create an iteration of Library, but I still came up with the exact same error. Please help. :)
var addButton = document.querySelector("#add");
var searchButton = document.querySelector("#search");
var titleInput = document.querySelector("#title");
function Book(title) {
this.title = title;
}
function Library() {
this.books = [];
}
Library.prototype.add = function(book) {
this.books.push(book);
}
var library = new Library();
//Library UI
var libraryUI = {
//Add a new book
addBook: function() {
var listItem = libraryUI.createNewBook(titleInput.value);
library.add(listItem);
console.log(library.books);
},
//Create a new book
createNewBook: function(title) {
var book = new Book(title);
return book;
}
};
addButton.addEventListener("click", libraryUI.addBook);
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Library App</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<h1>Personal Library</h1>
<label for="title">Title: </label>
<input type="text" id="title">
<button id="add">Add</button>
<button id="search">Search</button>
<p id="display"></p>
<script src="js/app.js"></script>
</body>
</html>
Shouldn't it be library.add instead of Library.add?
Also: why:
Library.prototype.add = function() {
this.add = function(book) {
this.books.push(book);
};
}
instead of:
Library.prototype.add = function(book) {
this.books.push(book);
}
?
If I change Library.add to library.add and console.log(library.books) I think this does what you want.

Creating paragraphs based on user input

I'm having trouble, grabbing the user input, and having the onclick operator create additional paragraphs with each click.
Here is my HTML code.
<!DOCTYPE html>
<html lang='en'>
<head>
<title>Add Paragraph </title>
<meta charset='utf-8' >
<script src="../js/addPara.js" type="text/javascript"></script>
</head>
<body>
<div>
<input type='text' id='userParagraph' size='20'>
</div>
<div id="par">
<button id='heading'> Add your paragraph</button>
</div>
</body>
</html>
Here is Javascript code:
window.onload = function() {
document.getElementById("addheading").onclick = pCreate;
};
function pCreate() {
var userPar= document.createElement("p");
var parNew = document.getElementById('userParagraph').value;
userPar.innerHTML = par;
var area = document.getElementById("par");
area.appendChild(userPar);
}
userPar.innerHTML = par;
should be
userPar.innerHTML = parNew;
In your code:
> window.onload = function() {
> document.getElementById("addheading").onclick = pCreate;
> };
Where it is possible (perhaps likely) that an element doesn't exist, best to check before calling methods:
var addButton = document.getElementById("addheading");
if (addButton) {
addButton.onclick = pCreate;
}
Also, there is no element with id "addheading", there is a button with id "heading" though.
> function pCreate() {
> var userPar= document.createElement("p");
> var parNew = document.getElementById('userParagraph').value;
> userPar.innerHTML = par;
I think you mean:
userPar.innerHTML = parNew;
if you don't want users inserting random HTML into your page (perhaps you do), you can treat the input as text:
userPar.appendChild(document.createTextNode(parNew));
.
> var area = document.getElementById("par");
> area.appendChild(userPar);
> }
Your variable names and element ids don't make a lot of sense, you might wish to name them after the data or function they represent.
I did it and it worked.
<html lang='en'>
<head>
<title>Add Paragraph </title>
<meta charset='utf-8' >
<script>
window.onload = function() {
document.getElementById("heading").onclick = pCreate;
}
function pCreate() {
var userPar= document.createElement("p");
var parNew = document.getElementById('userParagraph').value;
userPar.innerHTML = parNew;
var area = document.getElementById("par");
area.appendChild(userPar);
}
</script>
</head>
<body>
<div>
<input type='text' id='userParagraph' size='20'>
</div>
<div id="par">
<button id='heading'> Add your paragraph</button>
</div>
</body>
</html>```

Categories

Resources