What is the best way to display a Country's information from the dropdown menu in the Local Weather application?

I have been working on a Local Weather app that includes a dropdown menu where users can click on a location to view information such as City, Country, and temperature. However, I encountered an issue where the information does not appear consistently every time I click on a location.

Here is an overview of my code structure:

In order to display the current location and temperature, I utilized global variables within the function getLocation() and fetched the data in the function getWeather(). For the dropdown Menu functionality, I created an array named mainCities containing city details and appended them to the dropdown menu using function testMenu(). Each city entry has an onclick=testWeather('place') event attached to it, which triggers another function called

function testWeather(cityLocation)
. In this function, I attempted to access the global variables once again and run the weather retrieval logic from function getWeather().

If you would like to see the code implementation, please visit: http://codepen.io/kikibres/pen/EZMJZw

... (the remaining code snippets are preserved)...

Answer №1

There are a few issues with the code provided. Since all functions and variables are defined inside the document.ready, they cannot be accessed outside of it. This results in an error when attempting to call 'testWeather' on a click event, as it is not defined outside of the document.ready. To address this issue (make variables and functions global), it is recommended to define all variables outside of the document.ready. Only the following two lines should remain inside the document.ready:

$(".cityarea").html(getLocation);
  testMenu();

By making this adjustment, the issue of 'testWeather' not being defined will be resolved. Additionally, within the code, there is another problem where the property testLocation is used within the testWeather function without being defined. Instead of testLocation, the variable mainCities should be utilized. Implementing these two changes will ensure that the app runs smoothly without any errors. Below is the corrected JavaScript code. Furthermore, there is a minor issue with how the current city is being read from the code.

$(document).ready(function () { 
     $(".cityarea").html(getLocation);   
     testMenu();
 });
    var currentLat;
    var currentLong;
    var currentCity;
    var currentRegion;
    var currentCountry;

    var mainCities = {
        'San_Francisco': {
            'region': 'California',
            'country': "United States",
            'lat': 37.7749300,
            'lon': -122.4194200
        },
        'St._Louis': {
            'region': 'Missouri',
            'country': "United States",
            'lat': 38.6272700,
            'lon': -90.1978900
        },
        'Miami': {
            'region': 'Florida',
            'country': "United States",
            'lat': 25.7742700,
            'lon': -80.1936600
        },
        'Tokyo': {
            'region': 'Tokyo',
            'country': "Japan",
            'lat': 35.689500,
            'lon': 139.6917100
        }
    };

    function testMenu() {
        for (var place in mainCities) {
            var city = place.replace(/_/g, ' ');
            $('#testMenu').append("<li onclick=testWeather('" + place + "');><a href='#'>" + city + "</a></li>");
        }
    };

    function testWeather(cityLocation) {
        currentLat = mainCities[cityLocation].lat;
        currentLong = mainCities[cityLocation].lon;
        currentRegion = mainCities[cityLocation].region;
        currentCity = mainCities[cityLocation];
        currentCountry = mainCities[cityLocation].country;

        getWeather();

    };

    function getLocation() {
        $.getJSON('http://ip-api.com/json/?callback=?', function (data) {

            currentRegion = data.regionName;
            currentCity = data.city;
            currentCountry = data.country;
            currentLat = data.lat;
            currentLong = data.lon;

            //$("#cityname").text(currentCity);

            getWeather();

        });
    };

    function getWeather() {

        $("#cityname").text(currentCity);
        $("#state").text(currentRegion);
        $("#country").text(currentCountry);

        $.getJSON('http://api.openweathermap.org/data/2.5/weather?lat=' + currentLat + '&lon=' + currentLong + '&units=imperial&APPID=e656b9ee098cf2341fcfdb365b96b4a8', function (json) {

            var showfahrenheit = true;
            var tempfahrenheit = Math.round(json.main.temp);
            var temcelcius = Math.round((tempfahrenheit - 32) * 5 / 9);

            $("#temp").html(tempfahrenheit);

            $('#unit-switch').on('click', function () {
                if (showfahrenheit === false) {
                    $("#temp").html(tempfahrenheit);
                    showfahrenheit = true;
                } else {
                    $("#temp").html(temcelcius);
                    showfahrenheit = false;
                }

                $("#unit-toggle").toggleClass("toggle");
                //$('#temp').toggleClass('toggle');
            });

        });
    };

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Understanding the positioning of HTML elements using CSS

If you have the HTML snippet below: ... <fieldset> <div>above or below</div> <div>content</div> </fieldset> ... Is there a way to use CSS to position the <div>above or below</div> above or below the < ...

Utilizing a database for storing information from a website, such as usernames, passwords, responses, comments, and more

Can you link a website to an Access database? I currently use an Access database in Visual Basic and I want one database for all my applications. Is this possible? If so, does anyone have any code or examples to share? ps: This is for a school project, so ...

Interaction with three.js objects by clicking

I am looking for a way to show or hide objects by simply clicking a button. For example, when the button is clicked on the GUI, obj1 should be hidden and obj2 revealed. I tried using object.traverse(object.visible=false); but it doesn't seem to be ...

Using ng serve to upload multipart files in Angular 2

I am currently working on the front end of a file uploading service and have encountered a strange issue. When I restart the server using ng serve, it throws an error related to generated components within the app component. The error message can be seen h ...

Parsing JSON data from a stream

I have been working with an API lately that provides data in JSON format, and I know the fields it contains. I am trying to deserialize this data into a list format. I checked out the Newtonsoft.Json namespace for help, but unfortunately, the article I cam ...

What steps can be taken to resolve the problem of CSS sprite causing blurry images on mobile devices when using background-position?

In the world of CSS, working with regular images is usually straightforward - setting the width to 50px will display them perfectly on both desktop and mobile devices without any issues as long as the image quality is good. However, when it comes to using ...

How can React hook state be efficiently utilized in a debounced callback?

function Foo() { const [state, setState] = useState(0); const cb = useCallback(debounce(() => { console.log(state); }, 1000), []); return ...; } In the code snippet above, there is a potential issue where the state variable may become outda ...

Error: Unable to convert value to a string in Mongoose Schema

Hey everyone, I'm facing an issue while trying to send an array of strings with Mongoose Schema. It works fine for the tags but not for the selectedFile... Mongoose Schema: import mongoose from "mongoose"; const postSchema = mongoose.Schem ...

Utilizing PHP variables and CSS to dynamically adjust the background color according to various events triggered by SQL data

Hopefully my explanation is clear. <?php $rx_event_color = $rx_image_color = '#FF0000'; if ($a['rx_event_exists'] == 1) { $rx_event_color = '#00FF00'; } if ($a['rx_scanned'] == 1) { $rx_image_color = '#00FF ...

What is the process for displaying a JSON element within an HTML component in a Bootstrap modal?

My application is developed using CodeIgniter, and now I am looking to manipulate data using AJAX in jQuery. How can I display JSON elements within an HTML element in a Bootstrap modal? Here is the HTML and jQuery code: <td class="center"> < ...

Disabling the authentication prompt in the browser

Apologies for the repetition, but I would like to pose a more general question. Is there any method on the client side of a web application to predict if requesting a resource will result in a 401 status code and trigger an unattractive authentication pro ...

The returned error object from express does not include the error message

I recently posted a question related to an error issue. I am now wondering if I should have edited that question instead. Regarding the code snippet below: app.use((err, req, res, next) => { res.status(err.status || 500); res.json({ message: e ...

Enhance the code for updating the content within a div element

I recently discovered that utilizing jQuery allows for updating the content within a div. My goal now is to enhance this script so the content remains consistent, even while loading or not. Take a look at my current code: function changeContent () { va ...

Defining the flow and functionality

I'm currently attempting to define a function signature using Flow. I had anticipated that the code below would generate an error, but surprisingly, no errors are being thrown. What could be causing this issue? // This function applies another functi ...

Extracting information from a hyperlink without the need to actually click on it

Hello, I have recently started learning JavaScript and I am looking to accomplish a specific task. Currently, I am navigating on A.com/. Within the content of A.com/, there is a link labeled as A.com/B. Upon clicking on the link A.com/B, I can see ...

Generating dynamic divs in parallel

Despite encountering numerous posts related to the issue at hand, none of them have solved my specific problem. I am aiming for 3 divs to display in each row, but the current code is causing each div to show up on a new line vertically: JQuery ...

Achieving background stretching across different browsers with background-size functionality

I'm faced with a dilemma regarding a background image that is 40px wide and 1200px high, which I want to use as the background for a website. Since most users' monitors are not larger than 1200px, I can easily fill the background by setting "back ...

How can I center a button instead of using "margin-left: 0" when its location changes on a smaller screen?

Website: When viewing the website on my desktop, the text over the top image - "Buckinghamshire Food Partnership believe that everyone is entitled to a Right to Food" and the button - "Get involved" are aligned to the left with a 10% margin. However, on a ...

Incorporating Content-Disposition headers to enable the file to be both downloaded and opened

I'm having trouble allowing users to both view and download files on a web page. I've tried setting headers and using JavaScript, but can't seem to get it right. My goal is to have an HTML page with two links for each file - one to open in ...

Dynamic image sources in reusable Gatsby-Image Component

Recently, I have been exploring Gatsby-Image for an upcoming project and have started experimenting with its capabilities. My test project was successful, but now I want to utilize the <Image /> tag from Gatsby in a similar way to a standard <img ...