css Audio - Active file-generic CSS - Active Generic - Active HTML - Active JS - Active SVG - Active Text - Active file-generic Video - Active header Love html icon-new-collection icon-person icon-team numbered-list123 pop-out spinner split-screen star tv

Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              <html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>The Weather</title>
</head>

<body>

  <div class="grid-container">

    <div class="grid-item" id="containerSerach">
      <input id="userInput" type="text" placeholder="Enter a city or town" list="locations" autocomplete="off" />

      <datalist id="locations">

            </datalist>

      <button class="searchButton" id="search">Search</button>
      <button class="searchButton" id="searchLocation">Use My Location</button>
    </div>

    <div class="grid-item" id="containerWeather">
      <h1 id="locationName">Location</h1>
      <div id="weatherDesc">0&deg Clear <img src="" /></div>
      <hr style="width: 90%">
      <p id="windSpeed">0 m/s</p>
      <p id="humidity">0%</p>
    </div>

  </div>
  
  <script type="text/javascript" src="https://raw.githubusercontent.com/dantay0803/JavaScript_Tutorials/master/WeatherApp/city.list.json?token=AIH5o_CWefcR5mlvhTueX34RJmdkXRPqks5bxh5twA%3D%3D"></script>
  <script type="text/javascript" src="index.js"></script>

</body>

</html>
            
          
!
            
              html,
body {
  height: 100%;
}
body {
  background: url("https://images.unsplash.com/photo-1533421455827-883c3a23c031?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=400&fit=max&ixid=eyJhcHBfaWQiOjE0NTg5fQ&s=11f017d62033498b3bcad926ae089e0c");
  background-repeat: no-repeat;
  background-size: 100% 100%;
  color: white;
  margin: 0;
}
.grid-container {
  display: grid;
  grid-template-columns: 1fr 2fr 1fr;
  grid-template-rows: 1fr 2fr 1fr;
  height: 100%;
  width: 100%;
  margin: 0;
  padding: 0;
}
.grid-item {
  height: 100%;
  width: 100%;
  margin: 0;
  padding: 0;
}

#containerSerach {
  grid-row-start: 1;
  grid-column-start: 3;
  justify-content: right;
  margin-top: 20px;
}
#userInput {
  box-shadow: 1px 5px rgba(0, 0, 0, 0.8);
  height: 25px;
  border-radius: 5px;
  margin-right: 5px;
}
.searchButton {
  box-shadow: 1px 5px rgba(0, 0, 0, 0.8);
  height: 25px;
  border-radius: 5px;
  border: none;
  background-color: cornflowerblue;
  color: white;
}

#search {
  margin-right: 5px;
}
#searchLocation {
  margin-top: 20px;
  width: 210px;
}
#containerWeather {
  border: 2px solid rgba(0, 0, 0, 0.4);
  border-radius: 8px;
  background-color: rgba(0, 0, 0, 0.4);
  font-size: 150%;
  grid-row-start: 2;
  grid-column-start: 2;
  box-shadow: 5px 5px rgba(0, 0, 0, 0.8);
}
#containerWeather h1,
p,
img,
div {
  padding: 10px;
}
#weatherDesc {
  display: flex;
  align-items: center;
  padding-top: 0;
  margin-top: 0;
}
#windSpeed {
  text-align: right;
}

#humidity {
  text-align: right;
}

            
          
!
            
              const API_KEY = "Get OpenWeather API Key";

// Get display elements
const locationName = document.getElementById('locationName');
const weatherDesc = document.getElementById('weatherDesc');
const windSpeed = document.getElementById('windSpeed');
const humidity = document.getElementById('humidity');

// Set up search list data
const dataList = document.getElementById("locations");
// Get weather data from input location
document.getElementById('search').addEventListener('click', function () {

    let selectedLocation = document.getElementById('userInput').value;

    fetch(`https://api.openweathermap.org/data/2.5/weather?q=${selectedLocation}&appid=${API_KEY}`)
        .then(function (response) {
            return response.json();
        })
        .then(function (data) {
            console.log(data);
            formatData(data);
    });
});

// Get the users geolocation
document.getElementById('searchLocation').addEventListener('click', function()
{
    if (navigator.geolocation)
    {
        navigator.geolocation.getCurrentPosition(locationSearch);
    }
});

// Search the weather based on the geoloaction results
function locationSearch(pos)
{
    fetch(`https://api.openweathermap.org/data/2.5/weather?lat=${pos.coords.latitude}&lon=${pos.coords.longitude}&appid=${API_KEY}`)
        .then(function (response) {
            return response.json();
        })
        .then(function (data) {
            console.log(data);
            formatData(data);
    });
}

// Add the data to the page elements
function formatData(data) {
    locationName.innerText = data.name;
    weatherDesc.innerHTML = `${Math.round(convertTemp(data.main.temp) * 100) / 100}\xB0 ${data.weather[0].main} <img src="https://openweathermap.org/img/w/${data.weather[0].icon}.png" alt="Icon displaying the type of weather" />`;
    windSpeed.innerText = `Winds at ${data.wind.speed} m/s`;
    humidity.innerText = `Humidity levels at ${data.main.humidity}%`;

    setBackground(data.weather[0].main);
}

// Convert temp from kelvins to celsius
function convertTemp(temp) {
    return temp - 273.15;
}

// Set the background image of the page based on the weather type
function setBackground(weather) {
    switch (weather.toLowerCase()) {
        case "thunderstorm with light rain":
        case "thunderstorm with rain":
        case "thunderstorm with heavy rain":
        case "light thunderstorm":
        case "thunderstorm":
        case "heavy thunderstorm":
        case "ragged thunderstorm":
        case "thunderstorm with light drizzle":
        case "thunderstorm with drizzle":
        case "thunderstorm with heavy drizzle":
            document.body.style.backgroundImage = "url('https://images.unsplash.com/photo-1516490981167-dc990a242afe?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=400&fit=max&ixid=eyJhcHBfaWQiOjE0NTg5fQ&s=b2aabd23d7ccd73ec5700a92d89a7b7f')";
            break;
        case "light intensity drizzle":
        case "drizzle":
        case "heavy intensity drizzle":
        case "light intensity drizzle rain":
        case "drizzle rain":
        case "heavy intensity drizzle rain":
        case "shower rain and drizzle":
        case "heavy shower rain and drizzle":
        case "shower drizzle":
        case "light rain":
        case "moderate rain":
        case "heavy intensity rain":
        case "very heavy rain":
        case "extreme rain":
        case "freezing rain":
        case "light intensity shower rain":
        case "shower rain":
        case "heavy intensity shower rain":
        case "ragged shower rain":
            document.body.style.backgroundImage = "url('https://images.unsplash.com/photo-1532203512255-3c9c9d666c50?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=400&fit=max&ixid=eyJhcHBfaWQiOjE0NTg5fQ&s=22ff4b5b6feac104694cd5f5448c250a')";
            break;
        case "light snow":
        case "snow":
        case "heavy snow":
        case "sleet":
        case "shower sleet":
        case "light rain and snow":
        case "rain and snow":
        case "light shower snow":
        case "shower snow":
        case "heavy shower snow":
            document.body.style.backgroundImage = "url('https://images.unsplash.com/photo-1516715094483-75da7dee9758?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=400&fit=max&ixid=eyJhcHBfaWQiOjE0NTg5fQ&s=b0149781d26df9c5310dd1f580f41c40')";
            break;
        case "clear sky":
        case "clear":
            document.body.style.backgroundImage = "url('https://images.unsplash.com/photo-1519770340285-c801df5ff3db?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=400&fit=max&ixid=eyJhcHBfaWQiOjE0NTg5fQ&s=fa57841fcac049ecb3f4bee8a168b01a')";
            break;
        case "few clouds":
        case "scattered clouds":
        case "broken clouds":
        case "overcast clouds":
        case "clouds":
            document.body.style.backgroundImage = "url('https://images.unsplash.com/photo-1532939198640-a7f0da02b62f?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=400&fit=max&ixid=eyJhcHBfaWQiOjE0NTg5fQ&s=ab023564ab06df26216d065b4925fa72')";
            break;
        default:
            document.body.style.backgroundImage = "url('https://images.unsplash.com/photo-1533421455827-883c3a23c031?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=400&fit=max&ixid=eyJhcHBfaWQiOjE0NTg5fQ&s=11f017d62033498b3bcad926ae089e0c')";
            break;
    }
}

// Add list of locations as search options
function addLocations()
{
    let locations = document.getElementById("locations");
    
  for (let iterator of locationData) {

        let city = `${iterator.name},${iterator.country}`;

        let option = document.createElement("option");
        option.innerText = city;

        locations.appendChild(option);
    }
 
}

addLocations();
            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.
Loading ..................

Console