search
HomeWeb Front-endJS TutorialTutorial: How to make a weather web application using JS and API (Collection)

In the previous article "Teach you how to use HTML, CSS and JS to make a random password generator (share)", I introduced you how to use html, css and js to make a random password. Password Generator. The following article will introduce to you how to use JS and API to make a weather web application. Let's see how to do it together.

Tutorial: How to make a weather web application using JS and API (Collection)

Today I will make a great weather app where we can search for any city, region or country and use Weather API Get its current weather. Additionally, to add some polish to it, I also used the Unsplash API as the background image for the site, which will be based on the location you enter. I added a tilt effect and a glassy look to the card. The programming languages ​​we will use in this project are HTML, CSS, and JS. So let's goo goo goo.

Look at the final look we will achieve

Demo address: https://wanghao221.github.io/Weather.io/

bilibili show video: https://www.bilibili.com/video/BV1xX4y1c7Z4

Note: I only mentioned a few in the article that you should/might use in your code Key points and steps. Since, this is a blog, not a code base, I want to keep it simple. If you want to refer to the entire code address https://github.com/wanghao221/Weather.io, go take a look!

Step 1 - Set up the environment and gather all resources

Using your favorite code editor, create a new application called "Weather App" or whatever you want desired name, then create these three files and add these resources to the folder:

  • index.html

  • style. css

  • script.js

Other resources we need:

  • Favicon

  • Loading GIF (optional)

  • Vanilla-Tilt.js file

Download all of them Resource address: https://download.csdn.net/download/qq_44273429/20463321

Step 2 - Start with index.html

Start with a common template for HTML files. Add a title if desired.

Before linking style.css and script.js, link the Google fonts you want. I have used the Poppins font, which is one of my favorite fonts. (Google Fonts)

HTML

<link
href="https://fonts.googleapis.com/css2family=Poppins:ital,wght@0,200;0,400;0,500;0,600;0,700;0,800;0,900;1,800&display=swap"
rel="stylesheet">

Now starting with body if you wish to add a loader to your website then you can add it to the body tag , and then write a script for it.

HTML

<body onload="myFunction()">

Make two separate divs. One for the heading title and one for the card. Add appropriate div tag below it.

Here I use a search button in SVG format. You can use this code for buttons in card div.

HTML

<button>
<svg stroke="currentColor" fill="currentColor" stroke-width="0" viewBox="0 0 16 16" height="1em"
width="1.5em" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" d="M10.442 10.442a1 1 0 011.415 0l3.85 3.85a1 1 0 01-1.414 1.415l-3.85-3.85a1 1 0 010-1.415z"
clip-rule="evenodd"></path>
<path fill-rule="evenodd" d="M6.5 12a5.5 5.5 0 100-11 5.5 5.5 0 000 11zM13 6.5a6.5 6.5 0 11-13 0 6.5 6.5 0 0113 0z"
clip-rule="evenodd"></path>
</svg>
</button>

Add weather icon to default icon display.

HTML

<div class="flex">
  <img class="icon lazy"  src="/static/imghwm/default1.png"  data-src="https://openweathermap.org/img/wn/04d.png"   alt=""  />
  <div class="description">多云</div>
</div>

Loading animation and Vanilla-Tilt js script. Add it before the end of the text. I added the Vanilla-Tilt Js files to the resources mentioned in step 1 above.

JS

<script>
        var preloader = document.getElementById(&#39;loading&#39;);
        function myFunction() {
            preloader.style.display = &#39;none&#39;;
        }
</script>
<script type="text/javascript" src="js/vanilla-tilt.js"></script>
    <script type="text/javascript">
        VanillaTilt.init(document.querySelector(".card"), {
            max: 15,
            glare: true,
            reverse: true,
            "max-glare": 0.5,
            speed: 400
        });
        VanillaTilt.init(document.querySelectorAll(".card"));
</script>

Step 3 - Set up the index text

Start with the style body and other elements.

Set the style of loading animation. You can style it using this code. Since the loading animation has a white background, I used #fff. I added the SVG image in the resources folder.

CSS

#loading{
  position: fixed;
  width: 100%;
  height: 100vh;
  background: #fff url(&#39;/loading.svg&#39;)
  no-repeat center;
  z-index: 99999;
}

Please refer to the Github repository for CSS code

Address: https://github.com/wanghao221/Weather.io

Step 4 - Get the Weather API and Unsplash API Key

Go to OpenWeatherMap and create an account. After logging in, click in the API Keys tab and you will see the API key. Copy the API Key and paste it in the second line of the JavaScript code mentioned below (apiKey: " <insert api key here>",</insert>)

Tutorial: How to make a weather web application using JS and API (Collection)Go to Unsplash Source. Here you can see how images can be recalled in different ways based on size, text, user preferences, favorites, etc.

Tutorial: How to make a weather web application using JS and API (Collection)

Step 5 - Start with JavaScript Coding

Integrate in JavaSciptAPIFor learning how to Web It is crucial that the application uses API. I've listed the entire code. You can go through it and understand the code.

我已将此调用"url('https://source.unsplash.com/1600x900/?city " + name + "')"用于背景图像。您可以根据需要自定义URL

我还使用了上海市的默认天气weather.fetchWeather("Shanghai");。您可以在此处添加任何城市的名称。每当您加载网站时,都会弹出这个城市的天气。

JS

let weather = {
  apiKey: "<Insert API Key here>",
  fetchWeather: function (city) {
    fetch(
      "https://api.openweathermap.org/data/2.5/weather?q=" +
        city +
        "&units=metric&appid=" +
        this.apiKey
    )
      .then((response) => response.json())
      .then((data) => this.displayWeather(data));
  },
  displayWeather: function (data) {
    const { name } = data;
    const { icon, description } = data.weather[0];
    const { temp, humidity } = data.main;
    const { speed } = data.wind;
    document.querySelector(".city").innerText = "Weather in " + name;
    document.querySelector(".icon").src =
      "https://openweathermap.org/img/wn/" + icon + ".png";
    document.querySelector(".description").innerText = description;
    document.querySelector(".temp").innerText = temp + "°C";
    document.querySelector(".humidity").innerText =
      "湿度: " + humidity + "%";
    document.querySelector(".wind").innerText =
      "风速: " + speed + " km/h";
    document.querySelector(".weather").classList.remove("loading");
    document.body.style.backgroundImage =
      "url(&#39;https://source.unsplash.com/1600x900/?city " + name + "&#39;)";
    document.body.style.backgroundRepeat = "none";
    document.body.style.backgroundSize = "100";
    document.body.style.width = "100%";
    document.body.style.height = "100%";
    document.body.style.backgroundRepeat = "no-repeat";
    document.body.style.backgroundSize = "cover";

  },
  search: function () {
    this.fetchWeather(document.querySelector(".search-bar").value);
  },
};

document.querySelector(".search button").addEventListener("click", function () {
  weather.search();
});

document
  .querySelector(".search-bar")
  .addEventListener("keyup", function (event) {
    if (event.key == "Enter") {
      weather.search();
    }
  });

weather.fetchWeather("Shanghai");

第 6 步 - 免费托管您的网站!

现在,当您完成编码后,您可以在您的网站上托管您自己的天气应用程序,或者您甚至可以在 Github 上免费托管它!!!

https://github.com/wanghao221/Weather.io

托管是可选的,但我建议将其发布并与您的朋友和家人共享,并将其添加到您的项目列表中。

即将推出的功能

这是我计划添加一些更酷的功能,例如

每当您打开网站时进行位置检测,它将显示其天气特定位置的相关天气新闻使背景图像更准确地显示位置使其对大多数设备(iPad 和平板电脑)的响应速度更快

项目中一些很酷的截图

Tutorial: How to make a weather web application using JS and API (Collection)

Tutorial: How to make a weather web application using JS and API (Collection)

Tutorial: How to make a weather web application using JS and API (Collection)

推荐学习:HTML/CSS视频教程JS视频教程

The above is the detailed content of Tutorial: How to make a weather web application using JS and API (Collection). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金. If there is any infringement, please contact admin@php.cn delete
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools