Live Weather Update With JavaScript

codinglabsolution

    Embark on a coding adventure! Follow our guide to build Live Weather Update With JavaScript. Unleash your creativity in web development.


Live Weather Update With JavaScript










Experience real-time weather updates with our JavaScript-powered Live Weather Update feature. Stay informed about current weather conditions seamlessly integrated into your web experience.

Source Code

Step 1 (HTML Code):

Here's a breakdown of the provided HTML code:


1. Document Type Declaration:

   - `<!DOCTYPE html>`: Declares the document type and version of HTML being used.


2. HTML Structure:

   - `<html lang="en">`: Defines the root element of the HTML document, specifying the language as English.

   - `<head>`: Contains meta-information and links to external resources.

     - `<meta charset="UTF-8">`: Specifies the character encoding of the document as UTF-8.

     - `<meta name="viewport" content="width=device-width, initial-scale=1.0">`: Sets the viewport to the device's width and initial zoom level.

     - `<title>Live Weather Update With JavaScript</title>`: Sets the title of the document.

     - `<link rel="stylesheet" href="style.css">`: Links an external CSS stylesheet for styling.

   - `<body>`: Contains the visible content of the HTML document.


3. Container Structure:

   - `<div class="container">`: Serves as the main container for the weather information.

     - `<div class="info-side">`: Contains additional weather information such as pressure, humidity, and wind speed.

       - Various `<div>` elements with classes like `precipitation`, `humidity`, and `wind` to display specific weather data.

     - `<div class="weather-side">`: Contains the main weather information display.

       - `<div class="weather-gradient">`: Represents a gradient overlay for the weather information.

       - `<div class="date-container">`: Displays the date, location, and weather icon.

         - `<h2 class="date-dayname">`, `<i class="fa-solid fa-location-dot">`, `<span class="location">`: Display date and location information.

         - `<div class="icon2">`: Container for the weather icon.

           - `<img src="...">`: Weather icon sourced from OpenWeatherMap API.

       - `<div class="weather-container">`: Displays temperature and weather description.

         - `<i class="weather-icon"></i>`, `<h1 class="weather-temp">`, `<h3 class="weather-desc">`: Display weather information.


4. JavaScript Integration:

   - `<script src="script.js"></script>`: Links an external JavaScript file for scripting functionality.


This HTML structure creates a weather update interface with various weather-related information displayed in a visually appealing manner.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=\, initial-scale=1.0">
    <title>Live Weather Update With JavaScript</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="container">
        <div class="info-side">
          <div class="today-info-container">
            <div class="today-info">
              <div class="precipitation">
                <span class="title">PRESSURE</span>
                <span class="value PRE">0 hpa</span>
                <div class="clear"></div>
              </div>
              <div class="humidity">
                <span class="title">HUMIDITY</span>
                <span class="value humidity">34 %</span>
                <div class="clear"></div>
              </div>
              <div class="wind">
                <span class="title">WIND</span>
                <span class="value speed">0 km/h</span>
                <div class="clear"></div>
              </div>
            </div>
          </div>
        </div>
        <div class="weather-side">
          <div class="weather-gradient"></div>
          <div class="date-container">
            <h2 class="date-dayname">Today</h2>
            <i class="fa-solid fa-location-dot"></i>
     
            <span class="location">Paris, FR</span>
            <div class="icon2">
              <img src="https://openweathermap.org/img/wn/04n.png" class="icon" />
            </div>
          </div>
          <div class="weather-container">
            <i class="weather-icon"></i>
            <h1 class="weather-temp">29°C</h1>
            <h3 class="weather-desc">Sunny</h3>
          </div>
        </div>
      </div>
      <script src="script.js"></script>
</body>
</html>

Step 2 (CSS Code):


This CSS code styles the Live Weather Update UI with a modern and sleek design. Here's a breakdown:


1. Font Imports:

   - `Montserrat` font family is imported from Google Fonts for use in the UI.

   - Font Awesome icons are imported from the Font Awesome CDN for iconography.


2. Body Styling:

   - Sets the height of the body to 100% of the viewport height and centers its content using CSS grid.

   - Applies a dark background color to the body.


3. Container Styling:

   - Styles the main container for the weather update UI.

   - Applies the Montserrat font family, border radius, box shadow, background color, and text color.


4. Weather Side Styling:

   - Positions the weather side container relative to its parent.

   - Sets dimensions, border radius, box shadow, and transition effects for animation.


5. Weather Gradient Styling:

   - Creates a gradient overlay for the weather side container.

   - Positions the gradient absolutely within the container and applies a border radius and opacity.


6. Date and Location Styling:

   - Positions the date and location information within the weather side container.

   - Applies styles to the date, day, and location elements.


7. Weather Container Styling:

   - Positions the weather icon and temperature information within the weather side container.

   - Applies styles to the weather icon, temperature, and weather description.


8. Info Side Styling:

   - Positions the information side container relative to its parent.

   - Sets dimensions, padding, and margin for layout.


9. Today Info Styling:

   - Styles the container for additional weather information such as pressure, humidity, and wind speed.

   - Applies padding, margin, and border radius.


10. Icon Styling:

    - Sets dimensions for icons within the UI.

    - Styles location icon and weather icon.


11. Location Styling:

    - Applies styles to location text such as font size and color.


Overall, this CSS code creates a visually appealing and cohesive design for the Live Weather Update UI, enhancing the user experience with clear and readable weather information.

@import url('https://fonts.googleapis.com/css?family=Montserrat:400,700,900&display=swap');
@import url('https://use.fontawesome.com/releases/v6.5.1/css/all.css');


body {
  height: 100vh;
  margin: 0;
  display: grid;
  place-items: center;
  background-color: #343d4b;
}

.clear {
  clear: both;
}

.container {
  font-family: "Montserrat", sans-serif;
  border-radius: 25px;
  box-shadow: 0 0 70px -10px #00000033;
  background-color: #222831;
  color: #ffffff;
  height: 400px;
}

.weather-side {
  position: relative;
  height: 100%;
  border-radius: 25px;
  width: 300px;
  box-shadow: 0 0 20px -10px #00000033;
  float: left;
  transition: transform 300ms ease;
  transform: translateZ(0) scale(1.02) perspective(1000px);
}

.weather-gradient {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  background-image: linear-gradient(to right, #44a08d, #093637);
  border-radius: 25px;
  opacity: 0.8;
}

.date-container {
  position: absolute;
  top: 25px;
  left: 25px;
}

.date-dayname {
  margin: 0;
}

.date-day {
  display: block;
}

.location {
  display: inline-block;
  margin-top: 10px;
}

.location-icon {
  display: inline-block;
  height: 2rem;
  width: auto;
  margin-right: 5px;
  color: #fff;
}

.weather-container {
  position: absolute;
  bottom: 25px;
  left: 25px;
}

.weather-icon.feather {
  height: 60px;
  width: auto;
}

.weather-temp {
  margin: 0;
  font-weight: 700;
  font-size: 4em;
}

.weather-desc {
  margin: 0;
}

.info-side {
  position: relative;
  float: left;
  height: 100%;
  padding-top: 25px;
}

.today-info {
  padding: 15px;
  margin: 0 25px 25px 25px;
  border-radius: 10px;
}

.today-info>div:not(:last-child) {
  margin: 0 0 10px 0;
}

.today-info>div .title {
  float: left;
  font-weight: 700;
  padding-right: 4rem;
}

.today-info>div .value {
  float: right;
}

.icon {
  height: 5rem;
  width: 5rem;
}

.loc {
  font-size: 20px;
  color: #fff;
  padding-top: 1rem;
}

Step 3 (JavaScript Code):


This JavaScript code utilizes the Geolocation API to retrieve the user's current position. It then constructs a URL for the OpenWeatherMap API using the latitude and longitude coordinates obtained from the Geolocation API. After that, it fetches weather data from the OpenWeatherMap API and updates the HTML elements with the fetched data. Here's a breakdown:


1. `navigator.geolocation.getCurrentPosition()`:

   - Retrieves the user's current position (latitude and longitude) using the Geolocation API.

   - Accepts a callback function as an argument to handle the retrieved position.


2. Fetching Weather Data:

   - Constructs the API URL for the OpenWeatherMap API using the latitude and longitude coordinates.

   - Sends a fetch request to the constructed API URL.

   - Converts the response to JSON format.


3. Handling Data:

   - Extracts relevant weather data such as city name, weather description, temperature, humidity, and wind speed from the JSON response.

   - Updates the corresponding elements in the HTML document with the fetched weather data using `querySelector()`.


Overall, this JavaScript code fetches and displays real-time weather information based on the user's current location.

navigator
  .geolocation
  .getCurrentPosition((position) => {
    const { latitude, longitude } = position.coords;
    const api = `https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&units=metric&appid=75001f11037ddf2d94a9c85b0a7ab311`;

    fetch(api)
      .then((res) => res.json())
      .then((data) => {
        const name = data.name;
        const { description } = data.weather[0];
        const { temp, humidity } = data.main;
        const { speed } = data.wind;
        document.querySelector(".location").innerText = `Weather in ${name}`;
        document.querySelector(".weather-temp").innerHTML = `${temp} &deg;C`;
        document.querySelector(".speed").innerHTML = `${speed} meter/sec`;
        document.querySelector(".humidity .value").innerHTML = `${humidity} %`;
        document.querySelector(".weather-desc").innerHTML = description;
      });
  });

Source Code: Download Files


Conclusion:

In conclusion, the Live Weather Update feature powered by JavaScript offers users real-time access to weather information based on their current location. By leveraging the Geolocation API and the OpenWeatherMap API, users can effortlessly retrieve details such as temperature, humidity, wind speed, and weather description directly within their web browser. This dynamic and interactive functionality enhances user engagement and provides valuable insights into current weather conditions, empowering users to make informed decisions about their outdoor activities or travel plans. With its seamless integration and intuitive design, the Live Weather Update feature demonstrates the power of JavaScript in delivering rich and personalized user experiences on the web.

Tags: #JavaScript #WeatherUpdate #WebDevelopment #Geolocation #OpenWeatherMap #APIIntegration

إرسال تعليق

ملفات تعريف الارتباط
نستخدم ملفات تعريف الارتباط (Cookies) لفهم كيفية استخدامك لموقعنا وتحسين تجربتك في المحتوى والإعلانات. باستمرارك في تصفح الموقع، فإنك توافق على استخدامنا لملفات تعريف الارتباط وفقًا لسياسة الخصوصية لدينا.
أُووبس!
يبدو أن هناك خطأ ما في اتصالك بالإنترنت. يرجى الاتصال بالإنترنت وبدء التصفح مرة أخرى.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.