This question already has answers here:
How do I add a delay in a JavaScript loop?
(32 answers)
Closed 1 year ago.
I am new with JavaScript programming. I am making a program for deaf and blind children community. It is text to display Letters program. It split text and show image on screen.
How it works:
HTML and JavaScript base program. Input sentence taken from user. JavaScript split it and send relevant image name to HTML for display.
Problem:
It shows all images at once without delay. When I use alert() it shows all images are being displayed. 3rd day going on I tried to implement delay timebase substraction or settimeout but not working. Perhaps I am doing something wrong. I need community help to fix this.
Code:
<html lang="en">
<head>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link rel="stylesheet" href="index.css" />
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
<title>Image Changer</title>
</head>
// How to change image SCR through javascript.
<body>
<input id="txt" name="txt" type="textbox" />
<img id="image1" src="./multimedia/alphabets/0.jpg" style="width:100px">
<button onclick="imagechange((document.getElementById('txt').value) , document.getElementById('image1.scr'))">Button</button>
<script type="text/javascript">
function imagechange(txt,image1){
var txt1 = "";
var txt2 = "";
var imagefolderlocation = "./multimedia/alphabets/";
for (var i = 0; i < txt.length;i++) {
txt1 = txt.charAt(i).toUpperCase();
alert(txt1);
document.getElementById('image1').src = imagefolderlocation + txt1 +".jpg";
if(txt1 == " " )
document.getElementById('image1').src = imagefolderlocation + "Blank.jpg";
}
}
</script>
</body>
</html>
setTimeout is async so that's probably the reason it did not work. To make it work, you can do something like this
<script type="text/javascript">
function delay(time) {
return new Promise(function(resolve) {
setTimeout(resolve, time);
});
}
async function imagechange(txt,image1){
var txt1 = "";
var txt2 = "";
var imagefolderlocation = "./multimedia/alphabets/";
for (var i = 0; i < txt.length;i++) {
txt1 = txt.charAt(i).toUpperCase();
await delay(1000);
document.getElementById('image1').src = imagefolderlocation + txt1 +".jpg";
if(txt1 == " " ) document.getElementById('image1').src = imagefolderlocation + "Blank.jpg";
}
}
</script>
I made a delay promise from the setTimeout and made your imageChange function async so I can await the delay promise during each loop.
I guess this is because DOM manipulation is synchronous and DOM rendering is asynchronous. Actually you can try this:
function imagechange(txt,image1){
var txt1 = "";
var txt2 = "";
var imagefolderlocation = "./multimedia/alphabets/";
for (var i = 0; i < txt.length;i++) {
txt1 = txt.charAt(i).toUpperCase();
alert(txt1);
document.getElementById('image1').src = imagefolderlocation + txt1 +".jpg";
if(txt1 == " " ) document.getElementById('image1').src = imagefolderlocation + "Blank.jpg";
console.log(document.getElementById('image1').src);
}
}
You can see the result in the console, image1.src did change but was not rendered.
To make it work, you can use the asynchronous function like this if you are using ES5:
function imagechange(txt,image1){
var txt1 = "";
var txt2 = "";
var imagefolderlocation = "./multimedia/alphabets/";
for (var i = 0; i < txt.length;i++) {
txt1 = txt.charAt(i).toUpperCase();
// Use closures to avoid the problems caused by the txt1 variable context
function imageChange(imageName) {
setTimeout(function () {
document.getElementById('image1').src = imagefolderlocation + imageName +".jpg";
if(txt1 === " " ) {
document.getElementById('image1').src = imagefolderlocation + "Blank.jpg";
}
}, 1000 * i); // Change image1.src after i seconds
}
imageChange(txt1);
}
}
Btw, you should use <!-- How to change image SCR through javascript. --> in HTML if you want to add comments.
Related
I need your help on this!
I'm generating an array which corresponds to a question number.
var arrayCharge = [];
for (var i = 2; i <= 45; i++) {
arrayCharge.push(i);
}
then I use this number to append the corresponding question, answer then click.
Then I'm getting a new value from the array like this
const randomQ = arrayCharge;
const random = Math.floor(Math.random() * randomQ.length);
It works and a new question is charged but the array is still the same.
I've tried this
var remQ = arrayCharge.indexOf(randomQ[random]);
arrayCharge.splice(remQ,1);
But It doesn't work ;-(
Thanks a lot for your help.
Nicolas
Here is the entire code to help comprehension! sorry for that, I should have done it from the begining.
<!DOCTYPE HTML>
<!--
Hyperspace by HTML5 UP
html5up.net | #ajlkn
Free for personal and commercial use under the CCA 3.0 license (html5up.net/license)
-->
<html>
<head>
<title>Repérez vos messages contraignants - Quiz</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
<link rel="stylesheet" href="assets/css/main.css" />
<noscript>
<link rel="stylesheet" href="assets/css/noscript.css" /></noscript>
</head>
<body class="is-preload">
<!-- Sidebar -->
<!-- <section id="sidebar">
</section> -->
<!-- Wrapper -->
<div id="wrapper">
<!-- Intro -->
<section id="intro" class="wrapper style1 fullscreen fade-up">
<div class="inner">
<header>
<button id="start">Commencer</button>
<p> </p>
</header>
<form action="" method="post">
<p id="Qnum"></p>
<p id="Q" data-qnumber="" data-type=""></p>
<section id="answer">
<input type="submit" id="1" name="R1" value="Non">
<input type="submit" id="2" name="R2" value="Parfois">
<input type="submit" id="3" name="R3" value="Souvent">
<input type="submit" id="4" name="R4" value="Oui">
</section>
</form>
</div>
</section>
<!-- Footer -->
<!-- Scripts -->
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/jquery.scrollex.min.js"></script>
<script src="assets/js/jquery.scrolly.min.js"></script>
<script src="assets/js/browser.min.js"></script>
<script src="assets/js/breakpoints.min.js"></script>
<script src="assets/js/util.js"></script>
<script src="assets/js/main.js"></script>
<script>
$(document).ready(function() {
if (localStorage.getItem("clic") >= 45) {
console.log('45');
sessionStorage.clear();
localStorage.clear();
}
var Q1 = [1, "My first question", "FP"];
var Q2 = [2, "My second question", "SP"];
var Q3 = [3, "My third question", "SE"];
var Q4 = [4, "My foutrh question", "DP"];
var Q5 = [5, "My fifth question", "FP"];
//etc... until Q45
if (sessionStorage.getItem("FP") == null) {
$("form").attr("action", "driversV2.php");
$("#answer").hide();
$("#start").click(function() {
$("#Qnum").append(1+" / 45");
$("#Q").append(Q1[1]).attr("data-qnumber", Q1[0]).attr("data-type", Q1[2]);
$("#answer").show();
$("header").hide();
var pageType = $("#Q").attr("data-type");
$("input").click(function() {
var reponse = this.id;
sessionStorage.setItem(pageType, reponse);
localStorage.setItem("clic", 1);
});
});
} else {
$("header").hide();
var clicNum = parseInt(localStorage.getItem("clic"));
var QNumber = clicNum + 1;
var arrayCharge = [];
for (var i = 2; i <= 45; i++) {
arrayCharge.push(i);
}
const randomQ = arrayChargeNew;
const random = Math.floor(Math.random() * randomQ.length);
console.log('valeur random new = '+randomQ[random]);
var QCharge = "Q" + randomQ[random];
var Charge = eval(QCharge);
localStorage.setItem("random",randomQ[random]);
$("#Qnum").append(QNumber+" / 45");
$("#Q").append(Charge[1]).attr("data-qnumber", Charge[0]).attr("data-type", Charge[2]);
//création de la variable du type de question
var pageType = $("#Q").attr("data-type");
//alert(sessionStorage.getItem(pageType));
if (localStorage.getItem("clic") < 44) {
$("form").attr("action", "driversV2.php");
if (sessionStorage.getItem(pageType) != null) {
var x = parseInt(sessionStorage.getItem(pageType));
$("input").click(function() {
var reponse = parseInt(this.id);
var addition = reponse + x;
sessionStorage.setItem(pageType, addition);
var clic = parseInt(localStorage.getItem("clic"));
localStorage.setItem("clic", clic + 1);
});
} else {
$("input").click(function() {
var reponse = this.id;
sessionStorage.setItem(pageType, reponse);
var clic = parseInt(localStorage.getItem("clic"));
localStorage.setItem("clic", clic + 1);
});
}
} else {
$("form").attr("action", "driversResultat.php");
if (sessionStorage.getItem(pageType) != null) {
var x = parseInt(sessionStorage.getItem(pageType));
$("input").click(function() {
var reponse = parseInt(this.id);
var addition = reponse + x;
sessionStorage.setItem(pageType, addition);
var clic = parseInt(localStorage.getItem("clic"));
localStorage.setItem("clic", clic + 1);
});
} else {
$("input").click(function() {
var reponse = this.id;
sessionStorage.setItem(pageType, reponse);
var clic = parseInt(localStorage.getItem("clic"));
localStorage.setItem("clic", clic + 1);
});
}
}
}
});
</script>
</body>
</html>
Nicolas, this is the sort of thing you should end up with:
// From my library js file
// returns a random number in the given range
function getRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// Variables for objects that need to be available throughout
let availableQuestions = [];
let rnd = 0;
let counter = 0;
// Populate the question array - how this is done depends on where the question data comes from
function createQuestions() {
availableQuestions.length = 0;
for (let i = 1; i <= 10; i++) {
availableQuestions.push({"questionnumber": i, "question": "Text for question " + i});
}
}
// Pick a random question and display that to the user
function getRandomQuestion() {
let osQuestions = availableQuestions.length;
let qnElement = document.getElementById("questionnumber");
let qElement = document.getElementById("question");
let sButton = document.getElementById("submit");
let rButton = document.getElementById("restart");
// If there are no more questions, stop
if (osQuestions == 0) {
qnElement.innerHTML = "Finished!";
qElement.innerHTML = "";
sButton.style.display = "none";
rButton.style.display = "inline";
} else {
// display a sequential question number rather than the actual question number
counter++;
rnd = getRandomNumber(0, osQuestions - 1);
let thisQuestion = availableQuestions[rnd];
qnElement.innerHTML = "Question: " + counter + " (Actually question: " + thisQuestion.questionnumber + ")";
qElement.innerHTML = thisQuestion.question;
}
}
// Process the user's answer and remove the question from the array
function submitAnswer() {
// ALSO Add in what needs to be done to update backend database etc when the user clicks submit
availableQuestions.splice(rnd, 1);
getRandomQuestion();
}
// Reset everything - for testing purposes only
function restart() {
let qnElement = document.getElementById("questionnumber");
let qElement = document.getElementById("question");
let sButton = document.getElementById("submit");
let rButton = document.getElementById("restart");
qnElement.innerHTML = "";
qElement.innerHTML = "";
sButton.style.display = "inline";
rButton.style.display = "none";
// Reset the displayed question number counter
counter = 0;
createQuestions();
getRandomQuestion();
}
// Needed to populate the array and display the first question
function runsetup() {
createQuestions();
getRandomQuestion();
}
window.onload = runsetup;
<div id="questionnumber"></div>
<hr>
<div id="question"></div>
<button id="submit" onclick="submitAnswer();">Submit</button>
<button id="restart" onclick="restart();" style="display:none;">Restart</button>
I've included a counter variable so that the user does't see the actual question number - just 1, 2, 3 etc but I've shown the actual question number so that you can see it working
Nicolas, this is what I think you should be doing:
// Create the array in whatever way you need to
var arrayCharge = [];
for (var i = 2; i <= 45; i++) {
arrayCharge.push({"questionnumber": i, "question": "Text of question " + i});
}
// Just confirm the length of the array - should be 44
console.log(arrayCharge.length);
// Generate a random number based on the length of the array
var rnd = Math.floor(Math.random() * arrayCharge.length);
// Get the question at the randomly generated index number
let thisQuestion = arrayCharge[rnd];
// Check that we have a random question
console.log(thisQuestion.questionnumber);
console.log(thisQuestion.question)
// Present the question to the user on the page
// The user completes question and clicks "Submit"
// Now remove the question, using the SAME index number
arrayCharge.splice(rnd,1);
// Check that the array has lost an entry - the size should now be 43
console.log(arrayCharge.length);
I'm working on a code for extract information from an .json file and print it on a website. I achived all but now I have a problem, the data is showing only 1 result, it create all boxes/places for the other information but only the first "box" have information.
<head>
<!-- Title and Extern files -->
<title>SSL Checker</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script type="text/javascript" src="js/db.json"></script>
</head>
<body>
<div id="header">
<h2>SSL Checker</h2>
</div>
<div id="form">
<p>Introduce the URL:</p>
<input id="txtbx" type="text">
<button type="submit" onClick="agregar_caja()">Send</button>
<div id="inf">
<p type="text" id="hl1"></p>
<p type="text" id="hl2"></p>
</div>
<script>
//Extract
console.log(MyJSON[1].url)
var cajas = 2
var boxsaved = MyJSON.length
fnc = function(info) {
hey = document.getElementById("hl1").innerHTML = info.url;
}
//box creator
sm = function agregar_caja() {
document.getElementById("inf").innerHTML += "<p type=text id='hl" + new String(cajas + 1) + "'><br>"
cajas = cajas + 1
}
//Loops
for (i = 0; i < boxsaved; i++) {
sm(MyJSON[i]);
}
for (i = 0; i < MyJSON.length; i++) {
fnc(MyJSON[i]);
}
</script>
</body>
And .json file:
var MyJSON = [{
"url": 'google.es',
},
{
"url": 'yahoo.com',
}]
The problem is that your first box is the only element that your fnc function alters - notice that it only uses the hl1 id to access and alter an element, never hl2+.
I'll try to keep to your original approach, so that you'll follow it more easily. You might do something like this:
var cajas = 2;
function sm(info) {
cajas = cajas + 1;
document.getElementById("inf").innerHTML += (
'<div id="hl' + cajas + '">' + info.url + '</div>'
);
}
for (var i = 0; i < MyJSON.length; i++) {
sm(MyJSON[i]);
}
It is very difficult to read all the code, but as i've got it, you want to add some elements with url's from your JSON.
Ok, we have parent element div with id='inf', lets use javascript function appendChild to add new elements.
And we will use document.createElement('p') to create new elements.
Here is the code, as I've understood expected behavior.
var infContainer = document.getElementById('inf');
var elNumber = 2;
function agregar_caja() {
MyJSON.forEach(function(item,i) {
var newElement = document.createElement('p');
newElement.innerHTML = item.url;
newElement.id = 'hl'+elNumber;
elNumber++;
infContainer.appendChild(newElement);
}
)}
I am trying to create a word puzzle game but more like equation puzzle
equation puzzle game image
How can I do this using any math formatting library like MathJax? Here's another picture for more insight
equation puzzle game solution
Currently working with jquery.
Here's my current output
Here's my html page
<!DOCTYPE html>
<html>
<head>
<title>Word Find</title>
<link rel="stylesheet" type="text/css" href="styles/style.css">
</head>
<body>
<div id='puzzle'></div>
<div id='words'></div>
<div><button id='solve'>Solve Puzzle</button></div>
<script language="javascript" type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" async
src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.2/MathJax.js?config=TeX-MML-AM_CHTML">
</script>
<script type="text/javascript" src="../src/wordfind.js"></script>
<script type="text/javascript" src="scripts/wordfindgame.js"></script>
<script>
var firstEqn = "`s=u_t+1/2g_t^2`";
var secondEqn = "`s=u_t+1/2g_t^2`";
var thirdEqn = "`v^2=u^2+2gs`";
var fourthEqn = "`v=u-g_t`";
var fifthEqn = "`s=ut-1/2g_t^2`";
var words = [firstEqn, secondEqn, thirdEqn, fourthEqn, fifthEqn];
// start a word find game
var gamePuzzle = wordfindgame.create(words, '#puzzle', '#words');
$('#solve').click( function() {
wordfindgame.solve(gamePuzzle, words);
});
// create just a puzzle, without filling in the blanks and print to console
var puzzle = wordfind.newPuzzle(
words,
{height: 18, width:18, fillBlanks: false}
);
wordfind.print(puzzle);
</script>
</body>
</html>
Here's the function that draws the puzzle
var drawPuzzle = function (el, puzzle) {
var output = '';
// for each row in the puzzle
for (var i = 0, height = puzzle.length; i < height; i++) {
// append a div to represent a row in the puzzle
var row = puzzle[i];
output += '<div>';
// for each element in that row
for (var j = 0, width = row.length; j < width; j++) {
// append our button with the appropriate class
output += '<button class="puzzleSquare" x="' + j + '" y="' + i + '">';
output += "`"+row[j]+"`" || ' ';
output += '</button>';
}
// close our div that represents a row
output += '</div>';
}
$(el).html(output);
};
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>moving word</title>
</head>
<body>
<p id="word">w3resource</p>
</body>
</html>
<script type="text/javascript" src="five.js"></script>
function MovingLetters() {
var text = document.getElementById("word").value;
var len = text.length;
var lastletter = text.charAt(len-1);
text = text.substring(0,len-1);
text = lastletter + text;
}
MovingLetters();
$(function() {
setInterval(MovingLetters, 1000);
});
Console gives me :
Cannot read property 'length' of undefined
No idea why it is undefined because I defined it 2 lines before that one while that one reflects to a <p> in the html code that runs before the js script runs. Can someone help?
using value is for input elements, you should use textContent, innerText or if you want the html innerHTML:
var text = document.getElementById("word").textContent;
function MovingLetters() {
var word = document.getElementById("word")
var text = word.textContent;
var len = text.length;
var lastletter = text.charAt(len - 1);
text = text.substring(0, len - 1);
text = lastletter + text;
word.textContent = text
}
MovingLetters();
setInterval(MovingLetters, 1000);
<p id="word">w3resource</p>
You dont't want the value you want what's called innerHTML. you can achieve this by doing document.getElementById("word").innerHTML.length.
I am using geolocation to collect coordinates and make an API call to get the weather in Fahrenheit. I'm assigning the global variable tempNum this value within one of my functions that adds the temperature to the page using function getWeatherByCoordinates(latitude, longitude).
Later, I am trying to access this variable and pass the value as an argument into another function typeConversion for which I am attempting to convert the temperature value to Celsius. It is returning NaN and when debugging, I can't figure out why.
Here is my HTML and JS. I feel like since I declared my variable at the global level and set "return varName" in the function that I assigned the value to it, that the value should be accessible throughout my JS; but I may have done something wrong or misunderstood variable scope. Please assist.
var place = document.getElementById("meat");
var header = document.getElementById("header");
var weather = document.getElementById("Weather");
var latitude;
var longitude;
var coordinates = document.getElementById("coordinates");
function success(position) {
latitude = position.coords.latitude;
longitude = position.coords.longitude;
getWeatherByCoordinates(latitude, longitude);
};
//else {
// //Write Code to alternatively show a Zip-Code Search Box;
//};
navigator.geolocation.getCurrentPosition(success);
var city = document.getElementById("city");
var weatherDescription = document.getElementById("weather-description");
var roundTempF;
var roundTempC;
var tempNum;
var tempStringFFull
function getWeatherByCoordinates(latitude, longitude) {
var fullURL = "http://api.openweathermap.org/data/2.5/weather?lat=" + latitude + "&lon=" + longitude + "&APPID=75ed54453a6e806917cfa439b3fb1dd9&units=imperial";
$.getJSON(fullURL, function (data) {
var tempString = data.main.temp;
var tempNum = parseInt(tempString);
roundTempF = Math.floor(tempNum);
stringF = roundTempF.toString();
tempStringFFull = stringF + "\xB0" + " F";
weather.innerText = tempStringFFull;
city.innerText = data.name;
weatherDescription.innerText = data.weather[0].description;
if (data.dt > data.sys.sunrise && data.dt < data.sys.sunset) {
$("#whole-page").removeClass("whole");
$("#whole-page").removeClass("night");
$("#whole-page").addClass("day");
}
else {
$("#whole-page").removeClass("whole");
$("#whole-page").removeClass("night");
$("#whole-page").addClass("night");
};
event.preventDefault();
});
return tempNum;
};
function typeConversion(tempNum) {
if (changeTempType.innerText === "Celsius") {
var tempStringC;
var celsiusDecimal = (tempNum - 32) * (5 / 9);
roundTempC = Math.floor(celsiusDecimal);
tempStringC = roundTempC.toString();
tempStringC += "\xB0" + " C";
weather.innerText = tempStringC;
changeTempType.innerText = "Farenheit";
return;
}
else if (changeTempType.innerText === "Farenheit") {
weather.innerText = tempStringFFull;
changeTempType.innerText = "Celsius";
return;
}
else {
weather.innerText = "We are unable to retrieve the weather at this time. Please try again later";
changeTempType.innerText = "Celsius";
return;
};
};
var changeTempType = document.getElementById("change-temp-type");
changeTempType.addEventListener("click", typeConversion, false);
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet"/>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<script defer src="https://use.fontawesome.com/releases/v5.0.6/js/all.js"></script>
<title>Weather</title>
</head>
<body id="whole-page" class="whole">
<div class="wrapper">
<h2 id="header">Check the Current Temperaturate by Zip Code</h2>
<label>Farenheit</label>
<input type="radio" name="temp-type" value="C" id="Celsius-radio"/><label>Celsius</label>-->
<button id="change-temp-type">Celsius</button>
<form>
<p>Enter the Zip Code to see the Weather there!</p>
<input id = "Zip-Code" type="text"/>
<input id = "submit-zip" type="button" value="Get Weather!"/>
</form>
<div>
<h3 id="city"></h3>
<h3 id= "Weather" class="temp-text"></h3>
<h4 id="weather-description"></h4>
</div>
</div>
<script src= "https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.js"> </script>
<script src="javascript/main.js"></script>
</body>
</html>
You have a couple of issues:
You re-declare var tempNum = in your function, meaning it will be a new variable only accessible inside the function scope (leaving the global one unchanged)
Your code inside of $.getJSON is using an asynchronous callback - that means it will run sometime later than the code below it. When you return tempNum, that code has not run yet.
Your return statement isn't really doing anything... just reassigning the global variable will be sufficient.
UPDATE - issue I missed at first:
You are naming your function parameter in typeConversion "tempNum". Again, that will result in a new variable, only accessible within the scope of that function. If you want to affect the global, then this function does not need any parameters at all, and tempNum will then refer to the global variable as intended.
I've tried to clear up all issues below.
var place = document.getElementById("meat");
var header = document.getElementById("header");
var weather = document.getElementById("Weather");
var latitude;
var longitude;
var coordinates = document.getElementById("coordinates");
function success(position) {
latitude = position.coords.latitude;
longitude = position.coords.longitude;
getWeatherByCoordinates(latitude, longitude);
};
//else {
// //Write Code to alternatively show a Zip-Code Search Box;
//};
navigator.geolocation.getCurrentPosition(success);
var city = document.getElementById("city");
var weatherDescription = document.getElementById("weather-description");
var roundTempF;
var roundTempC;
var tempNum;
var tempStringFFull
function getWeatherByCoordinates(latitude, longitude) {
var fullURL = "http://api.openweathermap.org/data/2.5/weather?lat=" + latitude + "&lon=" + longitude + "&APPID=75ed54453a6e806917cfa439b3fb1dd9&units=imperial";
$.getJSON(fullURL, function (data) {
var tempString = data.main.temp;
// removed "var tempNum"...
tempNum = parseInt(tempString);
roundTempF = Math.floor(tempNum);
stringF = roundTempF.toString();
tempStringFFull = stringF + "\xB0" + " F";
weather.innerText = tempStringFFull;
city.innerText = data.name;
weatherDescription.innerText = data.weather[0].description;
if (data.dt > data.sys.sunrise && data.dt < data.sys.sunset) {
$("#whole-page").removeClass("whole");
$("#whole-page").removeClass("night");
$("#whole-page").addClass("day");
}
else {
$("#whole-page").removeClass("whole");
$("#whole-page").removeClass("night");
$("#whole-page").addClass("night");
};
event.preventDefault();
});
//return tempNum;
};
// removed the argument "tempNum", just use the global
function typeConversion() {
if (changeTempType.innerText === "Celsius") {
var tempStringC;
var celsiusDecimal = (tempNum - 32) * (5 / 9);
roundTempC = Math.floor(celsiusDecimal);
tempStringC = roundTempC.toString();
tempStringC += "\xB0" + " C";
weather.innerText = tempStringC;
changeTempType.innerText = "Farenheit";
return;
}
else if (changeTempType.innerText === "Farenheit") {
weather.innerText = tempStringFFull;
changeTempType.innerText = "Celsius";
return;
}
else {
weather.innerText = "We are unable to retrieve the weather at this time. Please try again later";
changeTempType.innerText = "Celsius";
return;
};
};
var changeTempType = document.getElementById("change-temp-type");
changeTempType.addEventListener("click", typeConversion, false);
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet"/>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<script defer src="https://use.fontawesome.com/releases/v5.0.6/js/all.js"></script>
<title>Weather</title>
</head>
<body id="whole-page" class="whole">
<div class="wrapper">
<h2 id="header">Check the Current Temperaturate by Zip Code</h2>
<label>Farenheit</label>
<input type="radio" name="temp-type" value="C" id="Celsius-radio"/><label>Celsius</label>-->
<button id="change-temp-type">Celsius</button>
<form>
<p>Enter the Zip Code to see the Weather there!</p>
<input id = "Zip-Code" type="text"/>
<input id = "submit-zip" type="button" value="Get Weather!"/>
</form>
<div>
<h3 id="city"></h3>
<h3 id= "Weather" class="temp-text"></h3>
<h4 id="weather-description"></h4>
</div>
</div>
<script src= "https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.js"> </script>
<script src="javascript/main.js"></script>
</body>
</html>
Last note - this will work fine if the function where you need to access tempNum runs later, like in response to a user action. It may still be undefined for a few ms after your page loads, so if you try to use it right at page load time, it may still be undefined. You may want to initialize it to some default value in this case.
Hope this helps.