Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Xings Weather App #414

Open
wants to merge 11 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 1 addition & 11 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,13 +1,3 @@
# Weather App

Replace this readme with your own information about your project.

Start by briefly describing the assignment in a sentence or two. Keep it short and to the point.

## The problem

Describe how you approached to problem, and what tools and techniques you used to solve it. How did you plan? What technologies did you use? If you had more time, what would be next?

## View it live

Every project should be deployed somewhere. Be sure to include the link to the deployed project so that the viewer can click around and see what it's all about.
https://xingsweatherapp.netlify.app
Binary file removed assets/design-1/Group16.png
Binary file not shown.
Binary file removed assets/design-1/Group34.png
Binary file not shown.
Binary file removed assets/design-1/Group36.png
Binary file not shown.
Binary file removed assets/design-1/Group37.png
Binary file not shown.
Binary file removed assets/design-1/Group38.png
Binary file not shown.
Binary file added assets/design-1/search-white.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added assets/design-1/search.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added assets/design-1/searchicon-white.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
7 changes: 0 additions & 7 deletions assets/design-2/noun_Cloud_1188486.svg

This file was deleted.

23 changes: 0 additions & 23 deletions assets/design-2/noun_Sunglasses_2055147.svg

This file was deleted.

16 changes: 0 additions & 16 deletions assets/design-2/noun_Umbrella_2030530.svg

This file was deleted.

46 changes: 46 additions & 0 deletions index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Rubik:wght@300;400;900&display=swap" rel="stylesheet">
<link rel="stylesheet" href="./style.css">
<title>2024 XingS Weather APP</title>
</head>

<body>
<main>
<section class="weather-container" id="weatherContainer">
<!-- Search Icon -->
<img src="./assets/design-1/search-white.png" id="searchIcon" alt="Search Icon">

<!-- Side Menu -->
<div class="side-menu" id="sideMenu" style="display: none;">
<div id="closeButton" class="close-button">&#10006;</div>
<input type="text" class="search-bar" id="inputLocation" placeholder="Search city name"
aria-label="City Search">
<img src="./assets/design-1/searchicon-white.png" id="searchButton" alt="Search Button">
</div>

<!-- Favorite City Button -->
<button id="favButton" class="fav-button">></button>

<!-- Current Weather Data -->
<div id="weatherData" class="weather-data"></div>
</section>

<!-- Weekly Forecast -->
<section class="weather-forecast"></section>
</main>

<footer>
<p>&copy; 2024 XingS Weather APP. All rights reserved.</p>
</footer>

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

</html>
3 changes: 1 addition & 2 deletions pull_request_template.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,2 @@
## Netlify link
Add your Netlify link here.
PS. Don't forget to add it in your readme as well.
https://xingsweatherapp.netlify.app
155 changes: 155 additions & 0 deletions script.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
const API_KEY = "0544757e153b183d75a7a72598c90d82"
const BASE_URL = "https://api.openweathermap.org/data/2.5/"

// DOM Selectors
const searchIcon = document.getElementById("searchIcon")
const sideMenu = document.getElementById("sideMenu")
const closeButton = document.getElementById("closeButton")
const inputLocation = document.getElementById("inputLocation")
const searchButton = document.getElementById("searchButton")
const weatherData = document.getElementById("weatherData")
const forecast = document.querySelector(".weather-forecast")
const favButton = document.getElementById("favButton")

let favCities = ["Stockholm", "Paris", "London", "Dubai", "Beijing", "Tokyo"]
let currentFavIndex = 0

// Utility: Toggle element visibility
const toggleElementVisibility = (element, state) => {
element.style.display = state ? state : element.style.display === "none" ? "flex" : "none"
}

// Toggle search menu and icon
const toggleSearchMenu = () => {
toggleElementVisibility(sideMenu)
toggleElementVisibility(searchIcon)
}

// Event listeners on page load
document.addEventListener("DOMContentLoaded", () => {
searchIcon.addEventListener("click", () => {
toggleElementVisibility(searchIcon, "none") // Hide search icon
toggleElementVisibility(sideMenu, "flex") // Show the side menu
})

closeButton.addEventListener("click", () => {
toggleElementVisibility(sideMenu, "none") // Hide the side menu
toggleElementVisibility(searchIcon, "block") // Show the search icon again
})

searchButton.addEventListener("click", debounce(startSearch, 500)) // Debounced search
favButton.addEventListener("click", fetchFavCityWeather)

// Fetch initial weather data for the first favorite city
fetchWeather(favCities[0])
})

// Create API URL
const createApiUrl = (endpoint, city) =>
`${BASE_URL}${endpoint}?q=${city}&units=metric&appid=${API_KEY}`

// Fetch weather data
const fetchWeather = city => {
Promise.all([
fetchData(createApiUrl("weather", city)),
fetchData(createApiUrl("forecast", city))
]).then(([weatherData, forecastData]) => {
updateWeatherUI(weatherData)
updateForecastUI(forecastData)
})
}

// Unified fetch function with error handling
const fetchData = url => fetch(url)
.then(response => {
if (!response.ok) throw new Error("City not found")
return response.json()
})
.catch(error => {
alert("City not found. Please check your input.")
throw error
})

// Utility: Format time in 24-hour format using the correct timezone
const formatTime = (unixTime, timezoneOffset) => {
const localTime = new Date((unixTime + timezoneOffset) * 1000)
return localTime.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: false})
}

// Update weather data in the UI
const updateWeatherUI = data => {
const temp = Math.floor(data.main.temp)
const weatherDescription = data.weather[0].description.charAt(0).toUpperCase() + data.weather[0].description.slice(1)
const iconUrl = `http://openweathermap.org/img/wn/${data.weather[0].icon}@2x.png`
const timezoneOffset = data.timezone // Use the timezone offset for the city

weatherData.innerHTML = `
<h1>${temp}<span>ºC</span></h1>
<h2>${data.name}</h2>
<h3>
${weatherDescription}
<img src="${iconUrl}" alt="Weather Icon" class="current-weather-icon">
</h3>
<h4>Current Time: ${formatTime(data.dt,timezoneOffset)}</h4>
<h5>Sunrise: ${formatTime(data.sys.sunrise, timezoneOffset)} | Sunset: ${formatTime(data.sys.sunset, timezoneOffset)}</h5>
`
dayToNight(data.dt, data.sys.sunrise, data.sys.sunset, timezoneOffset)
}

// Day/Night Background Update
const dayToNight = (currentTime, sunrise, sunset, timezoneOffset) => {
const adjustedCurrentTime = currentTime + timezoneOffset
const adjustedSunrise = sunrise + timezoneOffset
const adjustedSunset = sunset + timezoneOffset

weatherContainer.style.background = adjustedCurrentTime < adjustedSunrise || adjustedCurrentTime > adjustedSunset
? "linear-gradient(180deg, #323667 0%, #6B6EA8 100%)"
: "" // Default to CSS value for day
}

// Update forecast data in the UI
const updateForecastUI = forecastData => {
forecast.innerHTML = "" // Clear the forecast section
forecastData.list.filter((_, index) => index % 8 === 0).forEach(entry => {
const day = new Date(entry.dt * 1000).toLocaleDateString("en-US", { weekday: "short" })
const iconUrl = `http://openweathermap.org/img/wn/${entry.weather[0].icon}@2x.png`
const temp = `${Math.floor(entry.main.temp)}°C`
const windSpeed = `${entry.wind.speed} m/s`

forecast.insertAdjacentHTML("beforeend", `
<div class="forecast-day">
<p>${day}</p>
<img src="${iconUrl}" alt="Weather Icon" class="forecast-weather-icon">
<p>${temp}</p>
<p>${windSpeed}</p>
</div>
`)
})
}

// Validate search input and trigger weather fetch
const startSearch = () => {
const city = inputLocation.value.trim()
if (city) {
fetchWeather(city)
inputLocation.value = "" // Clear input field after search
} else {
alert("Please enter a city name.")
}
}

// Fetch weather for next favorite city
const fetchFavCityWeather = () => {
// Increment the index first, so the first click moves to the next city
currentFavIndex = (currentFavIndex + 1) % favCities.length
fetchWeather(favCities[currentFavIndex])
}

// Debounce function
const debounce = (func, delay) => {
let debounceTimer
return () => {
clearTimeout(debounceTimer)
debounceTimer = setTimeout(func, delay)
}
}
Loading