Javascript Onclick Function not working when Toggling Temperature - javascript

I'm working on a weather api and I'm having trouble toggling between Celsius and Fahrenheit.
I used a separate function to get the location as well as call from the API.
I also added an onclick function within this second function. I can get it to toggle to one temperature but not back.
function getTemp(data) {
// API variables
var temp1 = data.main.temp;
var weatherUrl = data.weather[0].icon;
var tempInC = Math.round(temp1); // Temp in Celsius
var tempInF = Math.round(temp1 * 9/5 +32)
// Inner HTML variables
var weatherF = "The weather is " + tempInF + " ℉ <br>" +
"<img src='" + weatherUrl + "'/>";
var weatherC = "The weather is " + tempInC + " ℃ <br>" +
"<img src='" + weatherUrl + "'/>";
// Button DOM variables
var buttonText = document.getElementsByTagName("button")[0].innerText;
var buttonId = document.getElementById('btn');
x.innerHTML = weatherF;
buttonId.onclick = function toggleTemp() {
if(buttonText == "Convert to Celsius") {
x.innerHTML = weatherC;
buttonId.innerText = "Convert to Fahrenheit";
} else {
x.innerHTML = weatherF;
buttonId.innerText = "Convert to Celsius";
}
}
}
I used innerText because I thought it was the easiest way to toggle back and forth between temp. I can get the weather to convert to Celsius, but the else statement is not working. Fyi, I was not able to get the button text to change using the tag name which is why I resorted to using an id in the button click function. I'm still pretty new at Javascript. Any help would be appreciated.

You need to update the buttonText variable when you toggle the text of buttonId.
buttonId.onclick = function toggleTemp() {
if (buttonText == "Convert to Celsius") {
x.innerHTML = weatherC;
buttonText = buttonId.innerText = "Convert to Fahrenheit";
} else {
x.innerHTML = weatherF;
buttonText = buttonId.innerText = "Convert to Celsius";
}
}

Your variable x is undefined. In the future, try to avoid using the innerHTML property, which can break event listeners and be slow to render.
Neither buttonText nor x are defined in the scope of your onclick function, which might be why nothing happens. Have you checked the console for errors?
function getTemp(data) {
// API variables
var temp1 = data.main.temp;
var weatherUrl = data.weather[0].icon;
var tempInC = Math.round(temp1); // Temp in Celsius
var tempInF = Math.round(temp1 * 9/5 +32)
// Inner HTML variables
var weatherF = "The weather is " + tempInF + " ℉ <br>" +
"<img src='" + weatherUrl + "'/>";
var weatherC = "The weather is " + tempInC + " ℃ <br>" +
"<img src='" + weatherUrl + "'/>";
// Button DOM variables
var x = ...; // Declare x for the function scope here
var buttonText = document.getElementsByTagName("button")[0].innerText;
var buttonId = document.getElementById('btn');
x.innerHTML = weatherF;
buttonId.onclick = (function (x, wC, wF, btn) {
return function () {
// Change DOM
if(btn.innerText == "Convert to Celsius") {
x.innerHTML = wC;
btn.innerText = "Convert to Fahrenheit";
} else {
x.innerHTML = wF;
btn.innerText = "Convert to Celsius";
}
};
})(x, weatherC, weatherF, document.getElementsByTagName("button")[0])
}

Related

How to define a button and a function inside js (React)

I am using MapBox to render a map. I have made a onClick function wherein when clicked on the map it shows the geocode information shown in the screenshot below through api.
Now what I want is to have a button below the table and when click on it I want it to execute a particular function, I have defined it but when clicked on it says Function is not defined
Code
map.current.on('click', function(e) {
var coordinates = e.lngLat;
var lng = coordinates.lng;
var lat = coordinates.lat;
console.log(lat);
console.log(lng);
var d = fetch("https://api.mapbox.com/geocoding/v5/mapbox.places/" + lng + "," + lat + ".json?access_token={token_value}").then(response => response.json()).then(function(data) {
console.log(data)
var str = "<table border='1'><tr><td><center>Title</center></td><td><center>Content</center></td></tr>"
for (let i in data["features"]) {
str = str + "<tr><td style='padding:5px'>" + data["features"][i]["place_type"][0] + "</td><td style='padding:5px'>" + data["features"][i]["place_name"] + "</td></tr>"
}
str = str + "</table>"
// button
str = str + "<button onClick={myFunction}>Save</button>"
function myFunction() {
console.log('Saved pressed');
}
new mapboxgl.Popup()
.setLngLat(coordinates)
.setHTML(str)
.addTo(map.current)
});
console.log(d);
});
Fix code as below
// button
str += `<button onclick="myFunction()"}>Save</button>`;
I would guess the button (and the function name defined for it) are created with a different scope than where you have defined your function. One of these might work:
Define your function as const myFunction = () => console.log("saved pressed").
Try referencing your function as this.myFunction

Is there something wrong with this javascript?

So this is externally linked, that works fine. But when I run it in the browser, it does not show anything. Is there anything wrong with this code?
var myheading = "This is my webpage!";
var text = "This JavaScript file makes use of Variables";
var linktag = "http://www.google.com/";
var begineffect = "<strong>";
var endeffect = "</strong>";
var linebreak = "<br />";
function numberone(myheading) {
document.write("<h2>" +myheading+ "</h2>");
}
numberone(myheading)
function numbertwo(text) {
document.write("<strong>" +text+ "</strong>");
}
numbertwo(text)
function numberthree(linktag) {
document.write( +linktag+ );
}
numberthree(linktag)
There are two extra + to remove in the document.write of the 'numberthree' function, i.e.:
var myheading = "This is my webpage!";
var text = "This JavaScript file makes use of Variables";
var linktag = "http://www.google.com/";
var begineffect = "<strong>";
var endeffect = "</strong>";
var linebreak = "<br />";
function numberone(myheading) {
document.write("<h2>" +myheading+ "</h2>");
}
numberone(myheading)
function numbertwo(text) {
document.write("<strong>" +text+ "</strong>");
}
numbertwo(text)
function numberthree(linktag) {
document.write(linktag);
}
numberthree(linktag)

How to capitalize the first letter of a var in p5.js [duplicate]

This question already has answers here:
How do I make the first letter of a string uppercase in JavaScript?
(96 answers)
Closed 4 years ago.
I am building a weather forecast site using JavaScript's framework p5.js. I have a description about what's the weather like (ex. few clouds) but the problem is that the api I'm using has only lowercase description. I wan't them to be uppercase but i don't know how to capitalize them. Can somebody help me? (I tried many vanilla JavaScript methods)
var weather;
var apiPath = 'http://api.openweathermap.org/data/2.5/weather?q=';
var apiKey = '&appid=e0342ddf94a760131ffacfa0e12bddf4';
var unit = '&units=metric';
var input;
function setup() {
noCanvas(270,125);
var button = select('#submit');
button.mousePressed(weatherAskAndDraw);
input = select('#city');
}
function CapFirst(string)
{
return string.charAt(0).toUpperCase() + string.slice(1);
}
function keyDraw(){
if (weather){
var temp = weather.main.temp;
var humidity = weather.main.humidity;
var minTemp = weather.main.temp_min;
var maxTemp = weather.main.temp_max;
var country = weather.sys.country;
var city = weather.name;
var vis = weather.visibility;
var des = weather.weather[0].description;
var windSpeed = weather.wind.speed;
fill(255);
CapFirst(des);
document.getElementById("p1").innerHTML = "City: " + city;
document.getElementById("p2").innerHTML = "Description: " + des;
document.getElementById("p3").innerHTML = "Temperature: " + temp;
document.getElementById("p4").innerHTML = "Humidity: " + humidity;
document.getElementById("p5").innerHTML = "Wind Speed: " + windSpeed;
}
}
function weatherAskAndDraw(){
var url = apiPath + input.value() + apiKey + unit;
loadJSON(url, gotData);
keyDraw();
}
function gotData(data){
weather = data;
}
I have not worked with P5.js but as simple js
mode = "few clouds";
string = mode.charAt(0).toUpperCase() + mode.substr(1,mode.length).toLowerCase();
console.log(string);

Global variable does not increment

Most of the action is in the function next. The other functions are provided for context. The global variable tally increments as it should when the right answer is selected. However the variable nr is not incremented and I can't figure out way it is not.
You can see that I commented out that the next function returned an object with tally and nr and assigned those values in the event listener. When I did it that way, it worked. But it should work the other way as well, right.
var nr = 0;
var tally = 0;
function onLoadEvent(nr) {
//alert('onload');
var quiz = document.getElementById('quiz');
var question = allQuestions[nr];
var next = quiz.lastElementChild;
var qHeader = "<h2>" + question.question + "</h2>";
var q = "";
for(var i=0;i<question.choices.length;i++){
q = q + '<p><label for="a' + i + '">' +
'<input type="radio" id="a' + i + '" name="q" value="' +
i + '">' + question.choices[i] + '</label></p>';
}
quiz.innerHTML = qHeader + q + next.outerHTML;
//next = document.getElementById('next');
}
function getChecked(){
var radios = document.getElementsByName('q');
var radio;
for(var i=0;i<radios.length;i++){
if(radios[i].checked){
radio = radios[i];
break;
}
}
return radio;
}
function next(nr){
if (getChecked() !== undefined) {
var answer = getChecked();
if(answer.value == allQuestions[nr].correctAnswer){
tally = tally + 1;
}
nr = nr + 1;
if (nr>=allQuestions.length){
alert("You got " + tally + " points!");
} else {
onLoadEvent(nr);
}
} else {
alert('You need to check a radio button');
}
//return {nr: nr, tally: tally};
}
var form = document.getElementById('quiz');
form.addEventListener('click', function(event){
if(event.target.id === 'next'){
next(nr);
//nr = obj.nr;
//tally = obj.tally;
} else if(event.target.id === 'prev'){}
}, false);
window.addEventListener('load', function(event){onLoadEvent(nr);}, false);
You are accepting parameters with same name nr which is hiding global scope nr.
Solution to your problem is remove nr as parameter. So use function onLoadEvent() instead of function onLoadEvent(nr)

I need Javascript syntax and logic advice

I have a two part question. The first is that I tried to replace all of my document.write with innerHTML and now nothing generates on the page correctly. The second part of my question is that I can't figure out the logic on my toggleCurrent function so that I can hide show the currently displayed view. example - if the thumbnail view is visible I want to hide/show or if the full view is visible I want to hide/show that. http://jsfiddle.net/5M3k7/
//Creating generic Object
function Person(name,age,biog,thumb,char,bg,cider) {
this.fullName = name;
this.age = age;
this.biog = biog;
this.thumb = thumb;
this.char = char;
this.bg = bg;
this.cider = cider;
}
//Creating new Objects
var jay = new Person ("Jay Jones",24,"Story","img","guy","bg","Fleet",true);
var jai = new Person ("Jai Janes",23,"Story","img","gal","bg","Sleet",true);
var dan = new Person ("Dan Dones",19,"Story","img","guy","bg","Leet",true);
var den = new Person ("Den Danes",49,"Story","img","guy","bg","Treat",true);
var dun = new Person ("Dun Dunes",20,"Story","img","guy","bg","Meet",true);
var vim = new Person ("Vim Vanes",22,"Story","img","guy","bg","Meat",true);
//Defining arrays
var characters = [jay, jai, dan, den, dun, vim];
//For loop goes though character array and prints it out.
var thumbs = function() {
var full = document.getElementById('full');
var cLength = characters.length;
for (var i = 0; i < cLength; i++){
full.innerHTML = '<div class="wrap"><div class="cont">' + "Name: " + characters[i].fullName + '<br/>' + 'Age: ' + characters[i].age + '<br/>' + 'Cider: ' + characters[i].cider + '</div></div>';
}
return;
};
var full = function() {
var thumb = document.getElementById('fullthumb');
var cLength = characters.length;
for (var i = 0; i < cLength; i++){
thumb.innerHTML = '<div class="fullwrap"><div class="bg"><div class="fullcont">Name: '
+ characters[i].fullName + '<br/> Age:' + characters[i].age + '<br/>Cider:' + characters[i].cider + '<div class="char"></div></div></div></div>';
}
return;
};
//Toggle Function
function toggleMenuDiv() {
var full = document.getElementById('full');
var thumb = document.getElementById('fullthumb');
var butt = document.getElementById('button');
if (full.style.display == 'none') {
full.style.display = 'block';
thumb.style.display = 'none';
butt.innerHTML = 'THUMB VIEW<span class="arrow-e"></span>';
}
else {
full.style.display = 'none';
thumb.style.display = 'block';
butt.innerHTML = 'FULL VIEW<span class="arrow-e"></span>';
}
}
//Toggle Function
function toggleCurrent() {
var chng = document.getElementById('change');
var thumb = document.getElementById('fullthumb');
var full = document.getElementById('full');
while (full.style.display == 'none')
{
if(thumb.style.display == 'block') {
chng.innerHTML = 'HIDE<span class="arrow-n"></span>';
}else{
thumb.style.display = 'none';
chng.innerHTML = 'SHOW<span class="arrow-s"></span>';
}
}
}
Because you keep overriding the last thing entered in.
full.innerHTML = '<div class="wrap"><div class="cont">' + "Name: " + characters[i].fullName + '<br/>' + 'Age: ' + characters[i].age + '<br/>' + 'Cider: ' + characters[i].cider + '</div></div>';
You are need to append to the innerHTML
full.innerHTML = full.innerHTML + '<div class="...

Categories