123

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.

            
              <body id="background">
  <div class="container-fluid">
    <div class="row">
      <div class="col-12">
        <search>
          <form class="search" id="search">
            <input class='searchbar transparent' id='searchbar' type='text' autocomplete="off" required placeholder='ENTER CITY, COUNTRY' />
            <input class='button go' id='go' type="submit" value='GO' />
          </form>
        </search>
        <!-- Split dropright button -->
        <div class="btn-group dropleft">
          <button type="button" class="arrow dropdown-toggle dropdown-toggle-split" data-toggle="dropdown"
            aria-haspopup="true" aria-expanded="false" id="arrow">
            <button type="button" class="fav btn-sm" id="favCityButton">Add City</button>
            <span class="sr-only">Toggle Dropright</span>
          </button>
          <div class="dropdown-menu" id="dropdown">
            <!-- Dropdown menu links -->
            <!-- <a class="dropdown-item" href="#" id="city">Action</a> -->
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="row">
    <div class="col-12">
      <h2 class="location" id="location">Your Location</h2>
    </div>
  </div>
  <hr class="hr" id="hr">
  <div class="row temps">
    <div class="col-2 iconsDiv">
      <img src='https://place-hold.it/75x75' class="icon" alt='place holder' id="icons">
    </div>
    <div class="col-2">
      <p class="currentTemp" id="temp"></p>
    </div>
    <div class="col-2 tempType">
      <a class="btn btn-default btn-sm degTypes" href="#" role="button" id="degTypeF"></a>
      <span class="divider off">|</span>
      <a class="btn btn-default btn-sm degTypes" href="#" role="button" id="degTypeC"></a>
    </div>
    <div class="col-3 conditions" id="conditions"></div>
  </div>
  <div class="row forecast" id="forecast"></div>
  <div class="row highrow" id="highRow"></div>
  <div class="row lowrow" id="lowRow"></div>
  </div>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.js"></script>
  <script src="Weather_App.js"></script>
  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
</body>
            
          
!
            
              @import url('https://fonts.googleapis.com/css?family=Roboto:400,300,100');
@import url('https://cdnjs.cloudflare.com/ajax/libs/weather-icons/1.3.2/css/weather-icons.min.css');

body {
    color: white;
    font-family: 'Roboto';
    text-align: center;
    background: #0D47A1;
  }

  .container-fluid {
    padding: 2em;
  }

  .searchbar {
    margin-top: 2em;
    border: none;
    width: 40%;
    padding-left: 7%;
    color: white;
    border-bottom: 1px white solid;
    background: transparent;
    text-transform: uppercase;
  }

  ::placeholder {
    color: white;
    opacity: .7;
    padding-left: 1%;
  }
  
  *:focus {
    outline: none;
  }

  .go {
    margin-top: 2em;
    color: white;
    border: none;
    cursor: pointer;
    background: transparent;
  }

  .go:hover {
    color: rgba(255, 255, 255, .4);
  }

  .dropleft {
    margin-right: 50%;
  }

  .fa-trash {
    color: rgb(190, 7, 7);
  }

  button.fav:focus {
    outline: none;
  }

  .fav {
    margin-top: .2em;
    margin-left: -.5em;
    color: white;
    border: none;
    cursor: pointer;
    background: transparent;
  }

  .fav:hover {
    color: rgba(255, 255, 255, .4);
  }

  .arrow {
    margin-top: .2em;
    font-size: 1em;
    color: white;
    border: none;
    cursor: pointer;
    background-color: transparent;
  }

  .arrow:focus {
    outline: none;
  }

  .arrow:hover {
    color: rgba(255, 255, 255, .4);
  }
/* 
  .dropdown-menu {
    background-color: transparent;
    border: none;
  } */

  /* .dropdown-item {
    color: white;
  } */

  h2 {
    font-size: 30px;
  }

  .location {
    margin-top: .7em;
    margin-bottom: -.9em;
    margin-right: 10%;
    letter-spacing: .1em;
  }
  
  hr {
    border: 0; 
    margin-top: 3%;
    margin-left: 25%;
    height: 1px;
    width: 60%;
    background-image: -webkit-linear-gradient(left, steelblue, white, steelblue);
    background-image: -moz-linear-gradient(left, steelblue, white, steelblue);
    background-image: -ms-linear-gradient(left, steelblue, white, steelblue);
    background-image: -o-linear-gradient(left, steelblue, white, steelblue); 
  }

  .iconsDiv {
    padding-left: 7%;
    margin-right: -2em;
  }

  .icon {
    height: 80px;
    width: 80px;
  }

  .temps {
    justify-content: center;
  }

  .tempType {
    margin-top: 1.4em;
    margin-left: -2.3em;
    margin-right: -2.3em;
  }

  .tempType a {
    color: rgba(255, 255, 255, .4);
  }

  .btn {
    color: rgba(255, 255, 255, 1);
    margin: -7px;
    margin-top: -13px;
    font-size: 25px;
    text-align: center;
    outline: none;
  }

  .btn:hover {
    color: white;
  }

  .btn:focus {
    outline: 0;
  }

  .divider {
    font-size: 25px;
  }

  .currentTemp {
    font-size: 65px;
    color: rgba(255, 255, 255, 1);
    text-align: right;
  }

  .conditions {
    margin-right: -2em;
  }

  .today {
    font-size: 20px;
    margin-right: 30%;
  }

  .condition {
    font-size: 15px;
    font-weight: lighter;
    margin-left: 11%;
  }

  .wind {
    font-size: 15px;
    font-weight: lighter;
    margin-left: 15%;
  }

  .windDirection {
    font-size: 15px;
    font-weight: lighter;
    margin-left: 29%;
  }

  .humidity {
    font-size: 15px;
    font-weight: lighter;
    margin-left: 17%;
  }

  .forecast {
    margin-top: 1em;
    padding-left: 35%;
    padding-right: 20%;
    justify-content: center;
    font-weight: lighter; 
    font-style: italic;
    font-size: 18px;
  }

  .highrow {
    padding-left: 35%;
    padding-right: 20%;
    justify-content: center;
    font-weight: bold;
    font-size: 23px;
  }

  .lowrow {
    padding-left: 35%;
    padding-right: 20%;
    justify-content: center;
    font-weight: lighter;
    font-size: 20px;
    color: rgba(255, 255, 255, .7);
  }

  .tempType a.focus-tempType {
    color: rgba(255, 255, 255, 1);
  }
            
          
!
            
              document.addEventListener("DOMContentLoaded", (e) => {

  let searchbar = document.getElementById(`searchbar`)
  let dropdown = document.getElementById(`dropdown`)

  if (localStorage.getItem(`favoriteCities`)){
    let favorites = JSON.parse(localStorage.getItem(`favoriteCities`))
    

    for (let i = 0; i < favorites.length; i++) {
      let option = `<a class="dropdown-item" href="#" id="${favorites[i]}"><i class="fas fa-trash delete" aria-hidden="true"></i>${favorites[i]}</a>`
      dropdown.innerHTML += option
    }
  }

  //Dropdown arrow menu - local storage
  dropdown.addEventListener(`click`, (event) => {
    document.getElementById(`searchbar`).value = ``
    if (event.target.classList.contains(`delete`)) {
      let arrOfCities = JSON.parse(localStorage.getItem(`favoriteCities`))
      let deleteInd = arrOfCities.indexOf(event.target.parentNode.id)
      let trash = arrOfCities.splice(deleteInd, 1)
      localStorage.setItem(`favoriteCities`, JSON.stringify(arrOfCities))

      dropdown.removeChild(event.target.parentNode)
    } else {
      getCall(event.target.text)
    }
  })

  getLocalWeather()

  let maxF
  let minF
  let maxC
  let minC
  let fahrenheit
  let celsius
  let degTypeF = document.getElementById(`degTypeF`)
  let degTypeC = document.getElementById(`degTypeC`)
  let temp = document.getElementById(`temp`)
  let location = document.getElementById(`location`)
  

  //Declare to search for cities
  let form = document.getElementById(`search`)

  form.addEventListener(`submit`, submitEvent)


  function submitEvent(event) {
    searchbar = document.getElementById(`searchbar`).value
    event.preventDefault()
    getCall(searchbar)
  }


  //Local storage - add a button for favorite cities
  let favorites = JSON.parse(localStorage.getItem(`favoriteCities`))
  let favCityButton = document.getElementById(`favCityButton`)
  let arrow = document.getElementById(`arrow`)

  //Dropdown button
  arrow.addEventListener(`click`, () => {
    favorites = JSON.parse(localStorage.getItem(`favoriteCities`))
    })


  //"Add City" button
  favCityButton.addEventListener(`click`, function (e) {
    let searchbar = document.getElementById(`searchbar`).value
    let option = document.createElement(`a`)

      let city = document.getElementById(`city`)
      favorites = JSON.parse(localStorage.getItem(`favoriteCities`)) || []
      
      if (favorites.indexOf(location.innerText) === -1) {
        favorites.push(location.innerText)
        localStorage.setItem(`favoriteCities`, JSON.stringify(favorites))
        dropdown.appendChild(option)
        option.classList.add(`dropdown-item`)
        
        for (let i = 0; i < favorites.length; i++) {
          option.innerHTML = `<i class="fas fa-trash delete" aria-hidden="true"></i> ${favorites[i]}`
      }
        
      } else {
        alert(`This city is in your favorites!`)
      }
  })


  //API call for any city
  function getCall(location) {
    axios.get(`https://api.apixu.com/v1/forecast.json?key=bef89cdff8d8407684220054182409&q=${location}&days=7`)
      .then((response) => updateUI(response))
      .catch(error => {
      console.log(error)
      if (error.response.status === 400) {
        alert(`City not found. Try again!`)
      }
      })
  }


  function getLocalWeather() {
    //Grab user coordinates
    axios.get(`https://ipinfo.io`)
      .then(e => {
        let coords = e.data.loc.split(`,`)
        let lat = coords[0]
        let long = coords[1]

        //API for JSON object containing user's current weather data
        let api = `https://api.apixu.com/v1/forecast.json?key=bef89cdff8d8407684220054182409&q=` + lat + `,` + long + `&days=7`

        axios.get(api)
          .then(e => updateUI(e))
      })
  }

  // Toggle ºC & ºF (buttons)
  degTypeF.addEventListener(`click`, function (e) {
    temp.innerText = fahrenheit + `º`
    degTypeF.classList.add(`focus-tempType`)
    degTypeC.classList.remove(`focus-tempType`)

    let tempElements = document.getElementsByClassName(`hi-temps`)
    for (let i = 0; i < tempElements.length; i++) {
      tempElements[i].innerText = maxF[i]
    }

    tempElements = document.getElementsByClassName(`low-temps`)
    for (let i = 0; i < tempElements.length; i++) {
      tempElements[i].innerText = minF[i]
    }
  })

  degTypeC.addEventListener(`click`, function (e) {
    temp.innerText = celsius + `º`
    degTypeC.classList.add(`focus-tempType`)
    degTypeF.classList.remove(`focus-tempType`)

    let tempElements = document.getElementsByClassName(`hi-temps`)
    for (let i = 0; i < tempElements.length; i++) {
      tempElements[i].innerText = maxC[i]
    }

    tempElements = document.getElementsByClassName(`low-temps`)
    for (let i = 0; i < tempElements.length; i++) {
      tempElements[i].innerText = minC[i]
    }
  })

  function removeElementsChildren(id) {
    let element = document.getElementById(id)
    while (element.hasChildNodes()) {
      element.removeChild(element.childNodes[0])
    }
  }

  function updateUI(response2) {

    removeElementsChildren(`conditions`)
    removeElementsChildren(`forecast`)
    removeElementsChildren(`highRow`)
    removeElementsChildren(`lowRow`)
    let curLocation = response2.data.location.name
    let country = response2.data.location.country
    let weatherCondition = response2.data.current.condition.text
    let windMph = response2.data.current.wind_mph
    let windKm = response2.data.current.wind_kph
    let windDir = response2.data.current.wind_dir
    let humidity = response2.data.current.humidity

    let feelsLikeF = Math.round(response2.data.current.feelslike_f)
    let feelsLikeC = Math.round(response2.data.current.feelslike_c)



    // Declare temp variables
    fahrenheit = Math.round(response2.data.current.temp_f)
    celsius = Math.round(response2.data.current.temp_c)
    degTypeF.innerText = `ºF`
    degTypeC.innerText = `ºC`


    //Append current location
    if (country === `United States of America`) {
      country = `US`
      //Set default to fahrenheit, gray out celsius
      temp.innerText = fahrenheit + `º`
      degTypeF.classList.add(`focus-tempType`)
      degTypeC.classList.remove(`focus-tempType`)
    } else {
      temp.innerText = celsius + `º`
      degTypeF.classList.remove(`focus-tempType`)
      degTypeC.classList.add(`focus-tempType`)
    }
    location.innerText = curLocation + `, ` + country



    //Change dates to corresponding days
    let daysOfWeek = [`Mon`, `Tue`, `Wed`, `Thu`, `Fri`, `Sat`, `Sun`]

    //Append 6 day forecast weather
    let forecastRow = document.getElementById(`forecast`)
    let forecastCol = document.getElementById(`col`)
    let forecast = response2.data.forecast.forecastday.slice(1)
    let highRow = document.getElementById(`highRow`)
    let lowRow = document.getElementById(`lowRow`)

    // Clear out min/maxes
    maxF = []
    minF = []
    maxC = []
    minC = []


    //Loop through forecast days and set to bottom 
    for (let i = 0; i < forecast.length; i++) {
      let date = forecast[i].date
      let day = document.createElement(`div`)
      day.setAttribute(`class`, `col-md-2`)
      forecastRow.appendChild(day)
      let dayInfo = new Date(date)
      let dayName = dayInfo.getDay()
      day.innerText = daysOfWeek[dayName]

      //Set highs and lows for each forecast
      maxF.push(Math.round(forecast[i].day.maxtemp_f))
      minF.push(Math.round(forecast[i].day.mintemp_f))
      maxC.push(Math.round(forecast[i].day.maxtemp_c))
      minC.push(Math.round(forecast[i].day.mintemp_c))

      let hiTemp = document.createElement(`div`)
      let lowTemp = document.createElement(`div`)

      //Forecast high temps
      hiTemp.setAttribute(`class`, `col-md-2 hi-temps`)
      if (country === `US`) {
        hiTemp.innerText = maxF[i]
      } else {
        hiTemp.innerText = maxC[i]
      }
      highRow.appendChild(hiTemp)


      //Forecast low temps
      lowTemp.setAttribute(`class`, `col-md-2 low-temps`)
      if (country === `US`) {
        lowTemp.innerText = minF[i]
      } else {
        lowTemp.innerText = minC[i]
      }
      lowRow.appendChild(lowTemp)
    }


    //Append conditions
    let todaysDate = response2.data.forecast.forecastday[0].date
    let today = new Date(todaysDate) //Current Day
    let todaysName = today.getDay()

    let conditions = document.getElementById(`conditions`)
    conditions.innerHTML = `
    <div class="today">${daysOfWeek[todaysName]}</div>
    <div class="condition">${weatherCondition}</div>
    <div class="wind">Wind: ${windMph} Mph</div>
    <div class="windDirection">Wind Direction: ${windDir}</div>
    <div class="humidity">Humidity: ${humidity}%</div>`


    // Changing weather color background
    let hr = document.getElementsByClassName(`hr`)[0]
    let body = document.getElementById(`background`)

    let tempValue = fahrenheit
    let gradColors
    if (tempValue >= 80) {
      gradColors = ['#e58d1b', '#800000']
    } else if (tempValue >= 70) {
      gradColors = ['#f9c920', '#e58d1b']
    } else if (tempValue >= 60) {
      gradColors = ['#0D47A1', '#5a97f2']
    } else {
      gradColors = ['#072A60', '#0D47A1']
    }
    body.style.background = `-webkit-linear-gradient(left, ${gradColors[0]}, ${gradColors[1]})`
    hr.style.background = `-webkit-linear-gradient(left, ${gradColors[0]}, white, ${gradColors[1]})`

    //Changing weather pictures
    let icon = response2.data.current.condition.icon
    let iconsPH = document.getElementById(`icons`)
    iconsPH.setAttribute(`src`, icon)



    //tests

//You still have a few bugs you should fix relating to the Add City button.

// If the user happens to enter a Zip Code instead of a city name, the 
// correct city’s weather information shows, but it defaults to Celsius (Metric) 
// regardless if the city is in the USA or not.

// Other bugs I notice in other parts of your app:

// You still only show mph for the Wind speed regardless if the temperature is showing in Celsius

// When I shrink the browser width a bit, I see the following. 
// You definitely need to try to make the page more responsive for smaller screens.

  }
})
            
          
!
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.

Console