Skip to content

Show current weather information based on city using in JavaScript

Learn how to show current weather information and forecast using WeatherWidget using JavaScript/TypeScript. WeatherWidget .io provides a free, customizable, responsive weather widget that will always match your website.

Get embed code from WeatherWidget

Enter your city and click on GET CODE.

Your code will be generated. The embed code will look like this.

<a class="weatherwidget-io" href="" data-label_1="MUMBAI" data-label_2="WEATHER" data-theme="original" >MUMBAI WEATHER</a>
!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);;js.src='';fjs.parentNode.insertBefore(js,fjs);}}(document,'script','weatherwidget-io-js');

This code can be embedded on any HTML page. I’m sure it would work. But this script isn’t enough to dynamically choose a city and fetch its weather. A few tweaks need to be done. This script works based on the href value that you pass. Each City has its own URL – with place_id and city name in the URL.

Get the list of URLs for your cities from Forecast7

const values = [
    { id: "", name: "San Bruno" },
    { id: "", name: "Framingham" },
    { id: "", name: "Abilene" },
    { id: "", name: "Howell" },
    { id: "", name: "Montoursville" },
    { id: "", name: "Boston" }

Create a dropdown for list of cities

<select (change)="onChange($event)">
      <option value="" disabled>Choose your DC</option>
      <option *ngFor="let v of values" [value]="">{{}}</option>
      <a class="weatherwidget-io" href="" data-label_1="BOSTON" data-label_2="WEATHER" data-theme="pure" >BOSTON WEATHER</a>

Create a div for weather. We are going to change the href property for this div based on selected city and reload the weather widget. That’s the trick.

Create a new function to load weather

loadWeather(s, id) {
    var js, fjs = document.getElementsByTagName(s)[0];
        js = document.createElement(s); = id;
        js.src = '';
        fjs.parentNode.insertBefore(js, fjs);

Load weather on changing dropdown

public onChange(event): void { 
    const newVal =;
    var x = document.getElementsByClassName('weatherwidget-io');

    var dcName =  this.values.filter(function(value) {
      return == newVal;

    this.loadWeather('script', 'weatherwidget-io-js');

You can call loadWeather function on ngOnInit when you are using TypeScript

ngOnInit() {
    this.loadWeather('script', 'weatherwidget-io-js');

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.