If you want to display real-time temperature, humidity, weather description, and day/night status on your website, this tutorial will help you build a fully functional Temperature Widget using JavaScript and PHP.
This widget:
✔ Detects user location automatically via IP
✔ Fetches live weather data using the Open-Meteo API (no API key required)
✔ Displays:
We’ll use:
Let’s start by creating the necessary files for our temperature widget. Below is the directory structure we will be working with:
temperature-widget/ ├── index.html ├── script.js ├── weather.php └── style.css
The widget will fetch weather data from the Open-Meteo API and display it in a user-friendly format. Below are the steps to create this widget:
First, we will create the basic HTML structure for our temperature widget. This will include a container for the widget, sections for the header, main content, and footer where we will display the weather information.
<div class="temp-widget">
<div class="widget-header">
<span class="location">Loading...</span>
<span class="day-night">🌞</span>
</div>
<div class="widget-main">
<span class="temperature">--<sup>°C</sup></span>
<span class="weather">--</span>
</div>
<div class="widget-footer">
<span class="humidity">Humidity: --%</span>
<span class="datetime">--</span>
</div>
</div>
Include JavaScript (script.js) to fetch and display weather data:
<script src="script.js"></script>
Next, we will add CSS styles to make our temperature widget visually appealing and responsive. We will use a clean and modern design with a color scheme that complements the weather data being displayed. The CSS will also ensure that the widget looks good on both desktop and mobile devices.
.temp-widget {
background: #ffffff;
width: 280px;
padding: 20px;
border-radius: 15px;
box-shadow: 0 8px 20px rgba(0,0,0,0.15);
}
.widget-header {
display: flex;
justify-content: space-between;
font-weight: bold;
}
.widget-main {
text-align: center;
margin: 20px 0;
}
.temperature {
font-size: 40px;
font-weight: bold;
}
.weather {
display: block;
margin-top: 5px;
color: #555;
}
.widget-footer {
display: flex;
justify-content: space-between;
font-size: 14px;
}
Finally, we will write the JavaScript code to fetch weather data from our PHP backend (weather.php) and update the widget dynamically. The JavaScript will make an AJAX request to the PHP script, which will return the weather data in JSON format. We will then parse this data and update the HTML elements in our widget accordingly.
document.addEventListener('DOMContentLoaded', () => {
fetch('weather.php')
.then(response => response.json())
.then(data => {
document.querySelector('.location').textContent = data.location || 'Unknown';
document.querySelector('.temperature').innerHTML = `${data.temperature ?? '--'}<sup>°C</sup>`;
document.querySelector('.weather').textContent = data.weather || '--';
document.querySelector('.humidity').textContent = `Humidity: ${data.humidity ?? '--'}%`;
document.querySelector('.datetime').textContent = data.datetime || '--';
document.querySelector('.day-night').textContent = data.is_day ? '🌞' : '🌜';
})
.catch(() => {
document.querySelector('.location').textContent = 'Error';
document.querySelector('.temperature').innerHTML = '--<sup>°C</sup>';
document.querySelector('.weather').textContent = '--';
document.querySelector('.humidity').textContent = 'Humidity: --%';
document.querySelector('.datetime').textContent = '--';
document.querySelector('.day-night').textContent = '❓';
});
});
In the weather.php file, we will write the PHP code to fetch weather data from the Open-Meteo API based on the user’s location. We will use the user’s IP address to determine their location and then make a request to the Open-Meteo API to retrieve the current weather data. Finally, we will return this data as JSON to be consumed by our JavaScript code in script.js.
<?php
// Auto-detect IP address
$ip = $_SERVER['REMOTE_ADDR'];
// Get location info from ip-api.com (free, no API key required)
$geo_url = "http://ip-api.com/json/{$ip}?fields=status,message,country,regionName,city,lat,lon";
$geo_response = @file_get_contents($geo_url);
$geo_data = $geo_response ? json_decode($geo_response, true) : null;
if ($geo_data && $geo_data['status'] === 'success') {
$lat = $geo_data['lat'];
$lon = $geo_data['lon'];
$location = $geo_data['city'] . ', ' . $geo_data['country'];
} else {
// Fallback to New York if geolocation fails
$lat = 40.7128;
$lon = -74.0060;
$location = 'New York, USA';
}
// Open-Meteo API (no API key required)
$weather_url = "https://api.open-meteo.com/v1/forecast?latitude={$lat}&longitude={$lon}¤t_weather=true&hourly=relative_humidity_2m,weathercode";
$weather_response = @file_get_contents($weather_url);
$weather_data = $weather_response ? json_decode($weather_response, true) : null;
if ($weather_data && isset($weather_data['current_weather'])) {
$temperature = $weather_data['current_weather']['temperature'];
$is_day = $weather_data['current_weather']['is_day'] == 1;
$datetime = date('l, H:i', strtotime($weather_data['current_weather']['time']));
// Get humidity from hourly data (nearest hour)
$humidity = '--';
if (isset($weather_data['hourly']['time']) && isset($weather_data['hourly']['relative_humidity_2m'])) {
$now = $weather_data['current_weather']['time'];
$idx = array_search($now, $weather_data['hourly']['time']);
if ($idx !== false) {
$humidity = $weather_data['hourly']['relative_humidity_2m'][$idx];
}
}
// Weather description from weathercode
$weather_codes = [
0 => 'Clear sky',
1 => 'Mainly clear',
2 => 'Partly cloudy',
3 => 'Overcast',
45 => 'Fog',
48 => 'Depositing rime fog',
51 => 'Light drizzle',
53 => 'Drizzle',
55 => 'Dense drizzle',
56 => 'Freezing drizzle',
57 => 'Dense freezing drizzle',
61 => 'Slight rain',
63 => 'Rain',
65 => 'Heavy rain',
66 => 'Freezing rain',
67 => 'Heavy freezing rain',
71 => 'Slight snow fall',
73 => 'Snow fall',
75 => 'Heavy snow fall',
77 => 'Snow grains',
80 => 'Slight rain showers',
81 => 'Rain showers',
82 => 'Violent rain showers',
85 => 'Slight snow showers',
86 => 'Heavy snow showers',
95 => 'Thunderstorm',
96 => 'Thunderstorm with hail',
99 => 'Thunderstorm with heavy hail',
];
$weathercode = $weather_data['current_weather']['weathercode'];
$weather = $weather_codes[$weathercode] ?? 'Unknown';
} else {
$temperature = '--';
$weather = 'Unavailable';
$humidity = '--';
$is_day = true;
$datetime = date('l, H:i');
}
// Return data as JSON
header('Content-Type: application/json');
echo json_encode([
'location' => $location,
'temperature' => $temperature,
'weather' => $weather,
'humidity' => $humidity,
'is_day' => $is_day,
'datetime' => $datetime
]);
?>
Once you have completed the above steps, your temperature widget should be fully functional and display real-time weather information based on the user’s location. The widget will show the current temperature, weather description, humidity, date & time, and a day/night indicator icon.
All fully dynamic and automatic.
In this tutorial, we have successfully created a real-time temperature widget using JavaScript and PHP. This widget automatically detects the user’s location, fetches live weather data from the Open-Meteo API, and displays it in a visually appealing format. You can easily customize the design and functionality of the widget to suit your website’s needs. This is a great way to enhance user experience by providing relevant and timely information. Happy coding!
Looking for expert assistance to implement or extend this script’s functionality? Submit a Service Request
💰 Budget-friendly • 🌍 Global clients • 🚀 Production-ready solutions