Global variable assigned value in one function is not accessible in another - javascript

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.

Related

JS get random value from array and update array

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);

Unable to call JavaScript method based on button element "id"

I am following a tutorial from Head First Javascript. In the tutorial, the showBlogs() method is called via the following html code
HTML button
<input type="button" id="showall" value="Show all blog entries" onclick="showBlogs();" />
function showBlogs(numberOfEntries){
//sort the blogs in reverse chronological order (most recent first)
blogs.sort(function(blog1, blog2){
return blog2.date - blog1.date;
})
//set the number of entires if non specified
if(!numberOfEntries){
numberOfEntries = blogs.length;
}
//set blog entries
var currenetBlog = 0; blogListHTML = "";
while(currenetBlog < blogs.length && currenetBlog < numberOfEntries){
blogListHTML += blogs[currenetBlog].toHTML(currenetBlog % 2 == 0);
currenetBlog++;
}
//display blog entries
blogsDOM.innerHTML = blogListHTML;
}
However, when I create another button and access it via javascript and call the same method with the event handler - nothing happens.
Button
<button type="button" id="showAllBlogs">Show All Posts</button>
Access Button within Javascript
const showBlogsButton = document.getElementById('showAllBlogs');
Call the showBlogs method
showBlogsButton.addEventListener('click', showBlogs);
I did try creating another function say 'foo()' and I called foo() with the new button and I was able to invoke the method. But when I call the showBlogs() method, nothing happens.
JAVASCRIPT CODE
`
//dom elements
const blogsDOM = document.getElementById('blog');
const query = document.getElementById('searchInput');
const searchButton = document.getElementById('searchButton');
const showBlogsButton = document.getElementById('showAllBlogs');
// Constructor
function Blog(body, dateString){
this.body = body;
this.date = new Date(dateString);
this.toString = function(){
return this.date.getMonth() + '/' + this.date.getDate() + '/' + this.date.getFullYear() + '/' +
this.body;
};
this.toHTML = function(highlight){
var htmlPost = "";
//determine to highlight post
htmlPost += highlight ? "<p style='background-color: #EEEEEE'>" : "<p>";
//generate formatted html
htmlPost += this.date.getMonth() + '/' + this.date.getDate() + '/' + this.date.getFullYear() + '/' +
this.body + "</p>";
//return html
return htmlPost;
};
this.containsText = function(text){
return this.body.toLowerCase().indexOf(text.toLowerCase()) > -1;
};
}
//Array of blogs
var blogs = [
new Blog("Got the new cube I ordered", "01/25/1986"),
new Blog("This new cube works just fine", "02/22/2000"),
new Blog("This is going to be the third one", "03/23/2005"),
new Blog("This is the final one", "03/21/2020")
]
blogs.sort(function(blog1, blog2){ return blog2.date - blog1.date; })
function getDaysBetweenDates(date1, date2){
var daysBetween = (date2 - date1) / (1000 * 60 * 60 * 24);
return Math.round(daysBetween);
}
function formatDate(date){
return date.getDay() + '/' + date.getMonth() + '/' + date.getYear();
}
function searchForPost(event){
let matchingBlogs = [];
event.preventDefault();
const searchQuery = query.value;
blogs.forEach(blog =>{
if(blog.body.toLowerCase().indexOf(searchQuery.toLowerCase()) > -1){
matchingBlogs.push(blog);
}
} )
showBlogs(matchingBlogs.length, matchingBlogs);
}
//show list of blog
function showBlogs(numberOfEntries, blogsToShow = blogs){
//sort the blogs in reverse chronological order (most recent first)
blogs.sort(function(blog1, blog2){
return blog2.date - blog1.date;
})
//set the number of entires if non specified
if(!numberOfEntries){
numberOfEntries = blogs.length;
}
//set blog entries
var currenetBlog = 0; blogListHTML = "";
while(currenetBlog < blogs.length && currenetBlog < numberOfEntries){
blogListHTML += blogs[currenetBlog].toHTML(currenetBlog % 2 == 0);
currenetBlog++;
}
//display blog entries
blogsDOM.innerHTML = blogListHTML;
}
searchButton.addEventListener('click', searchForPost);
showBlogsButton.addEventListener('click', showBlogs);`
HTML CODE
`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Blog</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h3>Youtube - the Blog for Cube puzzlers</h3>
<div class="search-container">
<input type="text" id="searchInput" placeholder="Search for a blog"/>
<button type="button" id="searchButton">Search the blog</button>
</div>
<div id="blog"></div>
<input type="button" id="showall" value="Show all blog entries" onclick="showBlogs();" />
<button type="button" id="showAllBlogs">Show All Posts</button>
<script src="script.js"></script>
</body>
</html>`

I can't get setInterval to work for me

I have a function called start that is triggered when you push the start button. The start function calls another function called getRandomImage. I want getRandomImage to repeat every 5 seconds, but I just can't get the setInterval method to work for me. I've tried putting the interval on the start function, but that just causes it to fire off once, and doesn't repeat. I've tried putting the interval on the getRandomImages function, but then it doesn't do anything. Essentially I am trying to make a color blindness test that flashes a random image every 5 seconds until 30 images have passed or the user clicks a button. I've been banging my head against this for over 8 hours, and am really questioning my choice in programming languages right now, lol.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"
<title></title>
<link rel="stylesheet" href="ColorPerceptionTest.css">
</head>
<body>
<section>
<img src="Default.png" id="defaultimage">
<form>
<input type="button" id="Button1" value="" onClick="">
<input type="button" id="Button2" value="" onClick="">
<input type="button" id="Button3" value="" onClick="">
<br>
<input type="button" id="Start" value="Start" onClick="start()">
<input type="button" id="Help" value="Help" onClick="help()">
<br>
<p id="help"> </p>
</form>
</section>
<script>
var $ = function(id) {
return document.getElementById(id);
}
$("Button1").style.display = "none";
$("Button2").style.display = "none";
$("Button3").style.display = "none";
var imagesArray = ["3.gif", "05.gif", "5.gif", "6.gif", "7.gif",
"8.gif", "12.gif", "15.gif", "16.gif", "26.gif",
"29.gif", "42.gif", "45.gif", "73.gif",
"74.gif"];
var runTimer = setInterval(start, 5000);
function getRandomImage(imgAr, path) {
path = path || 'images/';
var num = Math.floor( Math.random() * imgAr.length );
var img = imgAr[ num ];
var imgStr = '<img src="' + path + img + '" alt = "">';
$("defaultimage").src = path + img;
$("Button1").style.display = "initial";
$("Button2").style.display = "initial";
$("Button3").style.display = "initial";
if(parseInt(img) < 8){
$("Button1").value = parseInt(img);
$("Button2").value = parseInt(img) - 2;
$("Button3").value = parseInt(img) + 1;
}else if(parseInt(img) > 7 && parseInt(img) < 29){
$("Button1").value = parseInt(img) - 2;
$("Button2").value = parseInt(img);
$("Button3").value = parseInt(img) + 1;
}else{
$("Button1").value = parseInt(img) - 5;
$("Button2").value = parseInt(img) - 9;
$("Button3").value = parseInt(img);
}
}
var start = function(){
$("help").innerHTML = "";
getRandomImage(imagesArray);
$("Start").style.display = "none";
$("Help").style.display = "none";
}
var help = function (){
$("help").innerHTML = "This is a test designed to help you determine" +
" if you have a problem with seeing colors. When you press start, a series of " +
"random images will be displayed. You have 5 seconds to read the number and " +
"select the correct button.";
}
</script>
</body>
Try moving the setInterval call to a point where start is defined...
Your code works fine in this fiddle.
var start = function(){
$("help").innerHTML = "";
getRandomImage(imagesArray);
$("Start").style.display = "none";
$("Help").style.display = "none";
}
var runTimer = setInterval(start, 5000);
Update: To make it more clear, had OP written function start() the posted code would have been properly hoisted. But, as he used a function expression, start is undefined when setInterval is called.
Another update: Here's a forked fiddle to correct the timer based on the button and the comments below.

sensing geolocation using google maps

I am creating a functionality to sense the users geolocation using google api but i am having a problem that although the code seems to be alright the output is not showing i.e i am getting nothing as my location. Here is my code
<!DOCTYPE html>
<HTML>
<HEAD>
<TITLE>Geolocation</TITLE>
</HEAD>
<BODY>
Get Location
<DIV id = "map">
<IFRAME id = "google_map" width = "400" height = "350" frameborder = "0" scrolling = "no" marginheight = "0" marginwidth = "0" src = "https://maps.google.co.in?output=embed"></IFRAME>
</DIV>
<SCRIPT type = "text/javascript">
var getter = function(pos) {
var user_lattitude = pos.coords.lattitude;
var user_longitude = pos.coords.longitude;
var user_coordinates = user_lattitude + ',' + user_longitude;
document.getElementById('google_map').setAttribute('src' , 'https://maps.google.co.in/?q=' + user_coordinates + '&z=60&output=embed');
}
document.getElementById('get_location').onclick = function() {
navigator.geolocation.getCurrentPosition(getter);
return false;
}
</SCRIPT>
</BODY>
</HTML>
It looks like you've just spelt latitude wrong.
pos.coords.lattitude ;
It should only have 1 t. If you change that your above code will work.

how to change the value of input box just for display in html 5 web page

I have a textfield in which i am entering data i want that if user enter 1000 then it show 1,000 in textfield but this same value 1000 is also used in calculations further so how to solve this if user enter 1000 then just for display it show 1,000 and if we use in calcualtion then same var shows 1000 for calculating.
<HTML>
<body>
<input type="text" id="test" value="" />
</body>
<script>
var c=document.getElementById(test);
</script>
</html>
so if c user enter 1000 then it should dispaly 1,000 for dispaly one and if user uses in script
var test=c
then test should show 1000
document.getElementById returns either null or a reference to the unique element, in this case a input element. Input elements have an attribute value which contains their current value (as a string).
So you can use
var test = parseInt(c.value, 10);
to get the current value. This means that if you didn't use any predefined value test will be NaN.
However, this will be evaluated only once. In order to change the value you'll need to add an event listener, which handles changes to the input:
// or c.onkeyup
c.onchange = function(e){
/* ... */
}
Continuing form where Zeta left:
var testValue = parseInt(c.value);
Now let's compose the display as you want it: 1,000
var textDecimal = c.value.substr(c.value.length-3); // last 3 characters returned
var textInteger = c.value.substr(0,c.value.length-3); // characters you want to appear to the right of the coma
var textFinalDisplay = textInteger + ',' + textDecimal
alert(textFinalDisplay);
Now you have the display saved in textFinalDisplay as a string, and the actual value saved as an integer in c.value
<input type="text" id="test" value=""></input>
<button type="button" id="get">Get value</input>
var test = document.getElementById("test"),
button = document.getElementById("get");
function doCommas(evt) {
var n = evt.target.value.replace(/,/g, "");
d = n.indexOf('.'),
e = '',
r = /(\d+)(\d{3})/;
if (d !== -1) {
e = '.' + n.substring(d + 1, n.length);
n = n.substring(0, d);
}
while (r.test(n)) {
n = n.replace(r, '$1' + ',' + '$2');
}
evt.target.value = n + e;
}
function getValue() {
alert("value: " + test.value.replace(/,/g, ""));
}
test.addEventListener("keyup", doCommas, false);
button.addEventListener("click", getValue, false);
on jsfiddle
you can get the actual value from variable x
<html>
<head>
<script type="text/javascript">
function abc(){
var x = document.getElementById('txt').value;
var y = x/1000;
var z = y+","+ x.toString().substring(1);
document.getElementById('txt').value = z;
}
</script>
</head>
<body>
<input type="text" id="txt" value="" onchange = "abc()"/>
</body>
This works with integer numbers on Firefox (Linux). You can access the "non-commaed"-value using the function "intNumValue()":
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
String.prototype.displayIntNum = function()
{
var digits = String(Number(this.intNumValue())).split(""); // strip leading zeros
var displayNum = new Array();
for(var i=0; i<digits.length; i++) {
if(i && !(i%3)) {
displayNum.unshift(",");
}
displayNum.unshift(digits[digits.length-1-i]);
}
return displayNum.join("");
}
String.prototype.intNumValue = function() {
return this.replace(/,/g,"");
}
function inputChanged() {
var e = document.getElementById("numInp");
if(!e.value.intNumValue().replace(/[0-9]/g,"").length) {
e.value = e.value.displayIntNum();
}
return false;
}
function displayValue() {
alert(document.getElementById("numInp").value.intNumValue());
}
</script>
</head>
<body>
<button onclick="displayValue()">Display value</button>
<p>Input integer value:<input id="numInp" type="text" oninput="inputChanged()">
</body>
</html>

Categories

Resources