In today’s digital age, Weather App have become an essential tool for staying informed about ever-changing weather conditions. As a beginner web developer, the idea of creating your weather app can be both exciting and educational.
In this blog post, I’ll guide you through the steps of creating a responsive weather app project using HTML, Bootstrap, and JavaScript. By creating this weather project, not only will you learn the basics of DOM manipulation, event handling, and CSS styling, but you’ll also gain valuable experience working with APIs.
In this weather app, users can enter the name of a city and get different weather details like temperature in Celsius, wind speed, humidity, and a 5-day forecast. But if you wish, you can easily add or remove the particular weather details because we’ll use the OpenWeatherMap API, so you’ll have access to a wide array of weather information.
Steps To Create Weather App in Bootstrap & JavaScript
To create your own weather app project using HTML, Bootstrap, and JavaScript, follow these step-by-step instructions:
- Create a folder. You can name this folder whatever you want, and inside this folder, create the mentioned files.
- Create an
index.html
file. The file name must be index and its extension .html - Create a
style.css
file. The file name must be style and its extension .css - Create a
script.js
file. The file name must be script and its extension .js
To start, add the following HTML codes to your index.html
file. Since we’ve used Bootstrap for this project, the design, and layout are almost ready and responsive. After saving the HTML file and opening it in your browser, you’ll see a header, a search box on the left side, and some placeholders for weather details.
<!DOCTYPE html>
<!-- Coding By CodingNepal - www.codingnepalweb.com -->
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Weather App Project | CodingNepal</title>
<link rel="stylesheet" href="style.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css">
<script src="script.js" defer></script>
</head>
<body>
<header class="bg-success text-center py-3">
<h1 class="fw-bold h3 text-white my-1">Weather Dashboard</h1>
</header>
<div class="container-fluid my-4 weather-data">
<div class="row">
<div class="col-xxl-3 col-md-4 px-lg-4">
<h5 class="fw-bold">Enter a City Name</h5>
<input type="text" id="city-input" class="py-2 form-control" placeholder="E.g., New York, London, Tokyo">
<button id="search-btn" class="btn btn-success py-2 w-100 mt-3 mb-2">Search</button>
</div>
<div class="col-xxl-9 col-md-8 mt-md-1 mt-4 pe-lg-4">
<div class="current-weather bg-success text-white py-2 px-4 rounded-3">
<div class="mt-3 d-flex justify-content-between">
<div>
<h3 class="fw-bold">_______ ( ______ )</h3>
<h6 class="my-3 mt-3">Temperature: __°C</h6>
<h6 class="my-3">Wind: __ M/S</h6>
<h6 class="my-3">Humidity: __%</h6>
</div>
</div>
</div>
<h4 class="fw-bold my-4">5-Day Forecast</h4>
<div class="days-forecast row row-cols-1 row-cols-sm-2 row-cols-lg-4 row-cols-xl-5 justify-content-between">
<div class="col mb-3">
<div class="card border-0 bg-secondary text-white">
<div class="card-body p-3 text-white">
<h5 class="card-title fw-semibold">( ______ )</h5>
<h6 class="card-text my-3 mt-3">Temp: __°C</h6>
<h6 class="card-text my-3">Wind: __ M/S</h6>
<h6 class="card-text my-3">Humidity: __%</h6>
</div>
</div>
</div>
<div class="col mb-3">
<div class="card border-0 bg-secondary text-white">
<div class="card-body p-3 text-white">
<h5 class="card-title fw-semibold">( ______ )</h5>
<h6 class="card-text my-3 mt-3">Temp: __°C</h6>
<h6 class="card-text my-3">Wind: __ M/S</h6>
<h6 class="card-text my-3">Humidity: __%</h6>
</div>
</div>
</div>
<div class="col mb-3">
<div class="card border-0 bg-secondary text-white">
<div class="card-body p-3 text-white">
<h5 class="card-title fw-semibold">( ______ )</h5>
<h6 class="card-text my-3 mt-3">Temp: __°C</h6>
<h6 class="card-text my-3">Wind: __ M/S</h6>
<h6 class="card-text my-3">Humidity: __%</h6>
</div>
</div>
</div>
<div class="col mb-3">
<div class="card border-0 bg-secondary text-white">
<div class="card-body p-3 text-white">
<h5 class="card-title fw-semibold">( ______ )</h5>
<h6 class="card-text my-3 mt-3">Temp: __°C</h6>
<h6 class="card-text my-3">Wind: __ M/S</h6>
<h6 class="card-text my-3">Humidity: __%</h6>
</div>
</div>
</div>
<div class="col mb-3">
<div class="card border-0 bg-secondary text-white">
<div class="card-body p-3 text-white">
<h5 class="card-title fw-semibold">( ______ )</h5>
<h6 class="card-text my-3 mt-3">Temp: __°C</h6>
<h6 class="card-text my-3">Wind: __ M/S</h6>
<h6 class="card-text my-3">Humidity: __%</h6>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
Next, add the following few CSS codes to your style.css
file to add custom styling to some elements like font family, and image width.
/* Import Google font - Open Sans */
@import url('https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;500;600;700;800&display=swap');
* {
font-family: 'Open Sans', sans-serif;
}
.current-weather img {
max-width: 120px;
margin-top: -15px;
}
Finally, add the following JavaScript code to your script.js
file to make the weather app functional, which means getting different weather details for an entered city.
const cityInput = document.querySelector("#city-input");
const searchButton = document.querySelector("#search-btn");
const currentWeatherDiv = document.querySelector(".current-weather");
const daysForecastDiv = document.querySelector(".days-forecast");
const API_KEY = "PASTE-YOUR-API-KEY"; // Paste your API here
// Create weather card HTML based on weather data
const createWeatherCard = (cityName, weatherItem, index) => {
if(index === 0) {
return `<div class="mt-3 d-flex justify-content-between">
<div>
<h3 class="fw-bold">${cityName} (${weatherItem.dt_txt.split(" ")[0]})</h3>
<h6 class="my-3 mt-3">Temperature: ${((weatherItem.main.temp - 273.15).toFixed(2))}°C</h6>
<h6 class="my-3">Wind: ${weatherItem.wind.speed} M/S</h6>
<h6 class="my-3">Humidity: ${weatherItem.main.humidity}%</h6>
</div>
<div class="text-center me-lg-5">
<img src="https://openweathermap.org/img/wn/${weatherItem.weather[0].icon}@4x.png" alt="weather icon">
<h6>${weatherItem.weather[0].description}</h6>
</div>
</div>`;
} else {
return `<div class="col mb-3">
<div class="card border-0 bg-secondary text-white">
<div class="card-body p-3 text-white">
<h5 class="card-title fw-semibold">(${weatherItem.dt_txt.split(" ")[0]})</h5>
<img src="https://openweathermap.org/img/wn/${weatherItem.weather[0].icon}.png" alt="weather icon">
<h6 class="card-text my-3 mt-3">Temp: ${((weatherItem.main.temp - 273.15).toFixed(2))}°C</h6>
<h6 class="card-text my-3">Wind: ${weatherItem.wind.speed} M/S</h6>
<h6 class="card-text my-3">Humidity: ${weatherItem.main.humidity}%</h6>
</div>
</div>
</div>`;
}
}
// Get weather details of passed latitude and longitude
const getWeatherDetails = (cityName, latitude, longitude) => {
const WEATHER_API_URL = `https://api.openweathermap.org/data/2.5/forecast?lat=${latitude}&lon=${longitude}&appid=${API_KEY}`;
fetch(WEATHER_API_URL).then(response => response.json()).then(data => {
const forecastArray = data.list;
const uniqueForecastDays = new Set();
const fiveDaysForecast = forecastArray.filter(forecast => {
const forecastDate = new Date(forecast.dt_txt).getDate();
if (!uniqueForecastDays.has(forecastDate) && uniqueForecastDays.size < 6) {
uniqueForecastDays.add(forecastDate);
return true;
}
return false;
});
cityInput.value = "";
currentWeatherDiv.innerHTML = "";
daysForecastDiv.innerHTML = "";
fiveDaysForecast.forEach((weatherItem, index) => {
const html = createWeatherCard(cityName, weatherItem, index);
if (index === 0) {
currentWeatherDiv.insertAdjacentHTML("beforeend", html);
} else {
daysForecastDiv.insertAdjacentHTML("beforeend", html);
}
});
}).catch(() => {
alert("An error occurred while fetching the weather forecast!");
});
}
// Get coordinates of entered city name
const getCityCoordinates = () => {
const cityName = cityInput.value.trim();
if (cityName === "") return;
const API_URL = `https://api.openweathermap.org/geo/1.0/direct?q=${cityName}&limit=1&appid=${API_KEY}`;
fetch(API_URL).then(response => response.json()).then(data => {
if (!data.length) return alert(`No coordinates found for ${cityName}`);
const { lat, lon, name } = data[0];
getWeatherDetails(name, lat, lon);
}).catch(() => {
alert("An error occurred while fetching the coordinates!");
});
}
searchButton.addEventListener("click", () => getCityCoordinates());
Please note that your weather app is currently unable to retrieve weather details because you have not provided your API key in the AP_KEY
variable. To get a free API key from OpenWeatherMap, sign up for an account at https://home.openweathermap.org/api_keys.
In the code, there are two API calls. The first call gets the geographic coordinates of the city entered by the user. These coordinates are then used in the second call to retrieve the weather details, which are subsequently displayed on the page. Feel free to experiment with the code to gain a better understanding of its functionality.
Conclusion and Final Words
In conclusion, this blog post has guided you through the process of creating your own weather app using HTML, Bootstrap, and JavaScript. By following the steps outlined here, I hope you have successfully created your own weather app and learned how to work with APIs.
In addition to this weather app project, you can explore other exciting Bootstrap and JavaScript API projects available on this website to enhance your web development skills. These include Bootstrap Websites, ChatGPT Clone, Functional Image Gallery, Currency Converter, and more.
If you encounter any difficulties while creating your own weather app or your code is not working as expected, you can download the source code files for this weather app project for free by clicking the Download button. You can also view a live demo of it by clicking the View Live button.
2 thoughts on “How to make Weather App in HTML JavaScript”