Show the Local Weather

In this example below you will see how to do a Show the Local Weather with some HTML / CSS and Javascript

This is the freeCodeCamp weather app.

Thumbnail
This awesome code was written by Ellyria, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright Ellyria ©
  • HTML
  • CSS
  • JavaScript
<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  <title>Show the Local Weather</title>
  <title>Show The Local Weather</title>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<!--[if lt IE 9]>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv.js"></script>
	<script src="/js/html5shiv.js"></script>
<![endif]-->

  
  
      <link rel="stylesheet" href="css/style.css">

  
</head>

<body>

  <header aria-label="Page heading.">
	<h1>Local Weather</h1>
</header>

<section aria-label="Section for weather image and data.">
	<h3>Current conditions in <span id="display-location"></span></h3>
	<img alt="Icon showing the current weather." aria-label="Icon showing the current weather." id="display-weather-icon" src="" />
	<p id="display-temperature"></p>
	<p id="display-weather-description"></p>

	<footer>
		<p aria-label="Attribution paragraph.">
			Created by <a aria-label="Link to author's freeCodeCamp profile." href="https://www.freecodecamp.com/ellyria" target="_blank">Ellyria</a> with hosting by <a href="#" target="_blank">CodePen</a>, geolocation by <a aria-label="Link to geolocation provider's website." href="https://ipinfo.io" target="_blank">ipinfo.io</a>, weather data by <a href="http://api.openweathermap.org" target="_blank">OpenWeatherMap</a>, and the background image by <a title="By Nandaro (Own work) [CC BY-SA 4.0 (http://creativecommons.org/licenses/by-sa/4.0)], via Wikimedia Commons" href="https://commons.wikimedia.org/wiki/File%3A20141101-0819_Oso_Lake.jpg" target="_blank">Nandaro</a> at <a href="https://commons.wikimedia.org/wiki/Main_Page" target="_blank">Wikimedia Commons</a><!--, <mark>and the proxy by <a aria-label="Link to the proxy used by this page." href="http://cors-anywhere.herokuapp.com/" target="_blank">CORS-anywhere</a>--></mark>.
		</p>
	</footer>
</section>
  
  

    <script  src="js/index.js"></script>




</body>

</html>

/*Downloaded from https://www.codeseek.co/Ellyria/show-the-local-weather-OgpJXw */
/************************* PHONE **************************/
* {
	box-sizing: border-box;
	}
footer, header, section {/*For browser backwards compatibility*/
	display: block;
	} 
body,h1,h3,p {/*CSS reset*/
	height: 100%;
	margin:0;
	padding:0;
	}
body {
	background-color: yellow;
	background-image: url("https://upload.wikimedia.org/wikipedia/commons/e/e5/20141101-0819_Oso_Lake.jpg");
	background-size: 100% 100%;
	background-position: center;
	background-repeat: no-repeat;
	font-family: Verdana, Geneva, sans-serif;
	}
#display-temperature {
	font-size: 200%;
	margin-top: 2%;
	}
#display-weather-description {
	font-size: 150%;
	margin: 2% auto 0 auto;
	}
#display-temperature-celsius, display-temperature-fahrenheit {
	display: inline;
	}
#display-temperature span {
	color: blue;
	cursor:pointer;
	}
footer {
	font-size: 90%;
	font-style: italic;
	margin:2% auto 1% auto;
	opacity: 0.5;
	text-align: left;
	width: 100%;
	}
h1 {
	font-size: 3.5vw;
	text-align: center;
	}
h3 {
	font-size: 110%;
	}
html {
	height: 100%;
	}
img {
	background-color: white;
	border: 4px solid darkblue;
	border-radius: 9px;
	margin: 2.5% auto 2% auto;
	width: 60%;
	}
section {
	background-color: #DFD9FE;
	border: 7px solid darkblue;
	border-radius: 9px;
	margin: 1% auto auto auto;
	padding: 2%;
	text-align: center;
	width: 70%;
	}
/************************* TABLET *************************/
@media screen and (min-width: 769px) {
	body {
		background-color: green;
		}
	footer {
		margin: 4% auto 1% auto;
		}
	h3 {
		font-size: 170%;
		}
	img {
		width: 40%;
		}
	section {
		width: 50%;
		}
	}
/************************* DESKTOP *************************/
@media screen and (min-width: 992px) {
	body {
		background-color: red;
		}
	footer {
		margin: 4% auto 1% auto;
		}
	h3 {
		font-size: 170%;
		}
	img {
		margin-bottom: 0;
		width: 30%;
		}
	section {
		width: 50%;
		}
	}
/*********************** WIDE SCREEN ***********************/
@media screen and (min-width: 1200px) {
	body {
		background-color: violet;
		}
	footer {
		margin:5% auto 1% auto;
		}
	h3 {
		font-size: 180%;
		}
	img {
		width: 20%;
		}
	section {
		width: 55%;
		}
	}


/*Downloaded from https://www.codeseek.co/Ellyria/show-the-local-weather-OgpJXw */
//--------------------------LOCATION----------------------//
	function loadLocation() {
		var api = new XMLHttpRequest();
		api.onreadystatechange = function() {
			if (this.readyState == 4 && this.status == 200) {
				response = JSON.parse(this.responseText);
				city = response.city;
				country = response.country;
				loc = response.loc;
				region = response.region;
				//Create the local latitude variable and initialize it with the value of everything before the comma in the location variable value:
				latitude = loc.split(',')[0];
				//Create the localglobal longitude variable and initialize it with the value of everything after the comma in the location variable value:
				longitude = loc.substr(loc.indexOf(",") + 1);
				//Create the local locationContainer variable and initialize it with the value of the element with the id of display-location:
				locationContainer = document.getElementById("display-location");
				//Give the specified element the value of the response in the form of: city, region - country:
				locationContainer.innerHTML = city + ", " + region + " (" + country + ")";
				}
			if (this.readyState == 4 && this.status == 400) {
				console.log('Error - a status of 400 was returned by the geolocation site.');
				}
			};
		//Create the openWeatherMapId variable and initialize it with an encoded string:
		var locationId = "801q26752p7n28";
		//Reassign the value of the openWeatherMapId value with its value after decoding it with the rot13 function:
		locationId = rot13(locationId);
		//Create the url variable and give it the value of the full URL needed to access the OpenWeatherMap API:
		var url = 'https://ipinfo.io/json?token=' + locationId;
		//var url = 'https://CORS-Anywhere.HerokuApp.com/https://ipinfo.io/json?token=' + locationId;
		api.open("GET", "https://ipinfo.io/json?token=801d26752c7a28", false);
		api.send();
		}
	loadLocation();

//--------------------------WEATHER-----------------------//
function loadWeather() {
	//Create the weatherXHR variable and give it the value of a new XMLHttp request:
	var weatherXHR = new XMLHttpRequest();
	//Create the openWeatherMapId variable and initialize it with an encoded string:
	var openWeatherMapId = "33qnsnp42390090n369145op9o71o33o";
	//Reassign the value of the openWeatherMapId value with its value after decoding it with the rot13 function:
	openWeatherMapId = rot13(openWeatherMapId);
	//Create the url variable and give it the value of the full URL needed to access the OpenWeatherMap API:
// var url = 'http://api.openweathermap.org/data/2.5/weather?lat=' + latitude + '&lon=' + longitude + '&APPID=' + openWeatherMapId;

	var url = 'https://CORS-Anywhere.HerokuApp.com/http://api.openweathermap.org/data/2.5/weather?lat=' + latitude + '&lon=' + longitude + '&APPID=' + openWeatherMapId;

	//Load the weatherXHR function when ready:
	weatherXHR.onreadystatechange = function () {

		//If ready, send the request:
		if (weatherXHR.readyState == XMLHttpRequest.DONE) {

			//If the server status is 200:
			if (weatherXHR.status == 200) {

				//Get the server response, split it into an array at commas, and store that in the response variable:
				var response = weatherXHR.responseText.split(",");

				//Return the Object corresponding to the JSON text and store it in the response variable:
				response = JSON.parse(response);

				//TEMPERATURE:
				//Create the temperatureKelvin variable and initialize it with a value of the temperatyure in Kelvin from the server response:
				var temperatureKelvin = response.main.temp;

				//TEMPERATURE - CELSIUS:
				//Create the global temperatureCelsius variable and initialize it with a value of the temperature converted to Celsius:
				temperatureCelsius = temperatureKelvin-273.15;
				//Convert the Celsius temperature to a whole number:
				temperatureCelsius = Math.round(temperatureCelsius);

				//TEMPERATURE - FAHRENHEIT:
				//Create the global temperatureFahrenheit variable and initialize it with a value of the temperature converted to Fahrenheit:
				//temperatureFahrenheit = ((temperatureKelvin-273.15)*1.8)+32;
				temperatureFahrenheit = (temperatureKelvin - 273.15) * 9/5 + 32;

				//Convert the Fahrenheit temperature to a whole number:
				temperatureFahrenheit = Math.round(temperatureFahrenheit);

				//TEMPERATURE - SET DEFAULT UNITS FOR PAGE LOAD:
				//Give the display-temperature-fahrenheit element the default value of the temperature in Fahrenheit:
				document.getElementById("display-temperature").innerHTML = temperatureFahrenheit + "&#176 <span>F</span>";

				//WEATHER DESCRIPTION:
				var weatherDescription = response.weather[0].main;
				document.getElementById("display-weather-description").textContent=weatherDescription;

				//WEATHER ICON:
				//Create the weatherIcon variable and initialize it with the value of the element that holds the weather icon:
				var weatherIconContainer = document.getElementById("display-weather-icon");
				//Create the weatherIconName variable and initialize it with the value of the icon name from the server response:
				var weatherIconName = response.weather[0].icon;

				//Create the sunriseTime variable and initialize it with the value of the local sunrise time from the server response:
				var sunriseTime = response.sys.sunrise;
				//Create the sunsetTime variable and initialize it with the value of the local sunset time from the server response:
				var sunsetTime = response.sys.sunset;
				//Create the timeOfCalculation variable and initialize it with the value of the dt property from the server response:
				var timeOfCalculation = response.dt;
				//If the time of calculation is equal to or later than sunrise time or less than or equal to sunset time:
				if (timeOfCalculation >= sunriseTime && timeOfCalculation <= sunsetTime) {
					//Replace n with d in the weatherIconName variable value:
					weatherIconName = weatherIconName.replace("n", "d");
					}
				else {
					//Replace d with n in the weatherIconName variable value:
					weatherIconName = weatherIconName.replace("d", "n");
					};

				//Create the weatherIcon variable and initialize it with the value of the icon name from the server response:
				var weatherIcon = weatherIconContainer.src="http://openweathermap.org/img/w/" + weatherIconName + ".png";
				}

			//Specify the condition and action to be taken if the weather server response is 400:
			else if (weatherXHR.status == 400) {
				console.log('There was an error 400 from the OpenWeatherMap site.');
				}
			//Specify the condition and action to be taken if the weather server response is not 200 or 400:
			else {
				console.log('Something other than 200 was returned by the OpenWeatherMap site.');
				}
			}
		};
		//Open the GET method, the URL, and provide credentials:
		weatherXHR.open("GET", url, true);
		//Send the data to the server:
		weatherXHR.send();
	};
//Display the weather when the page loads:
loadWeather();

//---------------AN ATTEMPT TO OBEY THE API RULES----------------//
	//Create the rot13 function:
	function rot13(str) {
		//Create the arr array:
		var arr=[];
		//For each character in the str variable, add its character code value to the array as an element:
		for (i=0; i < str.length; i++) {
			arr.push(str.charCodeAt(i));
			}
		//For each element in the array, test its range and add or subtract 13 accordingly:
		for (i=0; i < arr.length; i++) {
			var characterIsInLowRange = (arr[i] > 64) && (arr[i] < 78) || (arr[i] > 96) && (arr[i] < 110);
			var characterIsInHighRange = (arr[i] > 77) && (arr[i] < 91) || (arr[i] > 109) && (arr[i] < 123);
			if ( characterIsInLowRange ) {arr[i] = arr[i] + 13;}
			else if ( characterIsInHighRange ) {arr[i] = arr[i] - 13;}
			}
		//For each element in the arr array, convert its character code to a letter:
		for (i=0; i < arr.length; i++) {
			arr[i] = String.fromCharCode(arr[i]);
			}
		//Convert the array to a string by joining its elements and store the result in the str variable:
		str = arr.join('');
		//Return the value of the str variable:
		return str;
		}

//---------------TOGGLE TEMPERATURE UNITS---------------------//
function toggleUnits() {
	var degreesCelsius = "&#176<span>C</span>";
	var degreesFahrenheit = "&#176<span>F</span>";
	var target = document.getElementById("display-temperature");
	if (target.textContent.includes('F')) {
		target.innerHTML = temperatureCelsius + degreesCelsius;
		return target.innerHTML;
		}
	else {
		target.innerHTML = temperatureFahrenheit + degreesFahrenheit;
		return target.innerHTML;
		}
	};
document.querySelector("#display-temperature").addEventListener('click', toggleUnits);

Comments