Cover

in Dev

Sample Weather App using jQuery and HTML

This example walks you through the process of making a simple “Weather” app in minutes in HTML and JavaScript (jQuery) that makes REST API calls using AJAX.

What you will build ? A webapp which inputs a city/town name and displays the current weather with some additional details.

What you will need ?

  • Your favorite code editor
  • A HTTP Server

The HTML: (Note: Including jQuery and Bootstrap resources in the final demo)

    <body>
        <div class="container-fluid">
            <div class="row">
                <div class="col-md-6">
                    <h2>Demo Weather App</h2>
                    
                    <input type="text" id="placeInput" placeholder="Enter City Name" class="form-control" /><br>
                    <button class="btn btn-success" onclick="getInput();">Get Weather</button>
                    <div id="weatherData"></div>
                </div>
            </div>
        </div>    
        
    </body>

Before adding the JavaScript code let us analyze the sample response object we will be getting from our API to know the data we are most interested in (useful later for displaying.)

Sample Response Object

 

 

 

 

 

 

 

 

The Javascript

    <script>
        function getInput(){//Get value of city name entered
            //Clear previous weatherData
            document.getElementById("weatherData").innerHTML = ""; 
            var cityName = $("#placeInput").val();
            getWeather(cityName);
        };

        function getWeather(cityName){//Get actual weather data by calling API
            var url = "http://api.openweathermap.org/data/2.5/weather?q="+cityName+"&appid=94e6cc601757d2f2fbdea1a57d9ac55a&units=imperial";
            $.ajax({
    		    url: url,
    	    	    type: 'GET',
    	            success: function(response) {
                        //Get data from response object and display
                        var currentTemp = response.main.temp;
                        var maxTemp = response.main.temp_max;
                        var minTemp = response.main.temp_min;
                        var description = response.weather[0].description;

                        //Creating html to display
                        var html = "<h4><strong>Current Forecast: "+cityName.charAt(0).toUpperCase() + cityName.slice(1)+"</strong>"+
                                    currentTemp+ "  with a high of " + maxTemp +
                                    ", low of " + minTemp+" F and "
                                    +description+".</h3>";
                        //Set innerHtml
                        document.getElementById("weatherData").innerHTML = html; 
    	            },
    	            error: function(e,a){
    	              alert("An error occured");
    	            }
	    });
        };
    </script>

 

Sample Output:

Sample Output

DEMO