- Creating a JavaScript Countdown Timer for Beginners
Welcome to this step-by-step guide on building a simple yet effective JavaScript countdown timer. In this tutorial, we’ll use HTML for the structure, CSS for styling, and JavaScript for the functionality. Let’s dive in!
Create a index.html file first and then save it and start writing the code below
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<title>Countdown Timer</title>
</head>
<body>
<div class="countdown">
<div id="timer">
<span id="days">00</span>
<span class="label">days</span>
<span id="hours">00</span>
<span class="label">hours</span>
<span id="minutes">00</span>
<span class="label">minutes</span>
<span id="seconds">00</span>
<span class="label">seconds</span>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
Explanation:
- We create a basic HTML structure with a
<div>for the countdown timer. - We link an external CSS file (
styles.css) for styling. - The countdown timer consists of individual spans for days, hours, minutes, and seconds.

CSS Styling (styles.css)
body {
font-family: 'Arial', sans-serif;
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
background-color: #f4f4f4;
}
.countdown {
text-align: center;
}
#timer {
font-size: 2rem;
background-color: #333;
color: #fff;
padding: 10px;
border-radius: 5px;
display: inline-block;
}
.label {
margin: 0 5px;
}
Let’s break down each part of the CSS code:
body {
font-family: 'Arial', sans-serif;
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
background-color: #f4f4f4;
}
font-family: 'Arial', sans-serif;: Sets the font family for the entire page to Arial or a sans-serif fallback if Arial is not available.display: flex;: Uses Flexbox layout for the body, enabling flexible box model properties.align-items: center;: Centers the content vertically within the body.justify-content: center;: Centers the content horizontally within the body.height: 100vh;: Sets the height of the body to 100% of the viewport height (vhstands for viewport height).margin: 0;: Removes default margins, ensuring no extra space around the body.background-color: #f4f4f4;: Sets the background color of the body to a light gray.
Countdown Container Styling:
.countdown {
text-align: center;
}
.countdown: Targets an HTML element with the class “countdown.”text-align: center;: Centers the text within the element horizontally.
Timer Styling:
#timer {
font-size: 2rem;
background-color: #333;
color: #fff;
padding: 10px;
border-radius: 5px;
display: inline-block;
}
#timer: Targets an HTML element with the ID “timer.”font-size: 2rem;: Sets the font size to 2 times the default size.background-color: #333;: Sets the background color to a dark gray.color: #fff;: Sets the text color to white.padding: 10px;: Adds padding around the content inside the element.border-radius: 5px;: Rounds the corners of the element with a 5-pixel radius.display: inline-block;: Makes the element an inline block, allowing other elements to be next to it horizontally.
Label Styling:
.label {
margin: 0 5px;
}
.label: Targets HTML elements with the class “label.”margin: 0 5px;: Sets margins around the elements, adding 0 margin at the top and bottom and 5 pixels on the left and right.
These styles collectively contribute to a centered, visually appealing countdown timer with defined fonts, colors, and spacing. Adjustments can be made based on specific design preferences.
JavaScript Countdown Logic (script.js)
document.addEventListener('DOMContentLoaded', function () {
const countDownDate = new Date("Jan 1, 2023 00:00:00").getTime();
const x = setInterval(function () {
const now = new Date().getTime();
const distance = countDownDate - now;
const days = Math.floor(distance / (1000 * 60 * 60 * 24));
const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((distance % (1000 * 60)) / 1000);
document.getElementById("days").innerHTML = formatTime(days);
document.getElementById("hours").innerHTML = formatTime(hours);
document.getElementById("minutes").innerHTML = formatTime(minutes);
document.getElementById("seconds").innerHTML = formatTime(seconds);
if (distance < 0) {
clearInterval(x);
document.getElementById("timer").innerHTML = "EXPIRED";
}
}, 1000);
function formatTime(time) {
return time < 10 ? "0" + time : time;
}
});
Explanation:
- We set the target date for the countdown (modify the
countDownDatevariable). - The countdown updates every second, calculating the remaining days, hours, minutes, and seconds.
- The time is formatted to always display two digits for a cleaner look.
- If the countdown is over, an “EXPIRED” message is displayed.
2. JavaScript Tic Toe Game
In this JavaScript endeavor, you will build a Tic-Tac-Toe game—an engaging and timeless project that serves as an excellent introduction to basic game development.
This project stands out for illustrating how JavaScript elevates the user experience on web pages. Crafting a Tic-Tac-Toe game not only adds an enjoyable element but also proves beneficial for your portfolio. Particularly advantageous for those venturing into web development, this project showcases fundamental programming concepts within a familiar and relatable context.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
/* Basic styling for the game board */
#board {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 5px;
}
.cell {
width: 100px;
height: 100px;
border: 2px solid #333;
font-size: 2em;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
}
</style>
</head>
<body>
<h1>Tic-Tac-Toe Game</h1>
<div id="board"></div>
<script>
// Initialize the game board and current player
let board = ["", "", "", "", "", "", "", "", ""];
let currentPlayer = "X";
// Function to render the game board
function renderBoard() {
const boardElement = document.getElementById("board");
boardElement.innerHTML = "";
board.forEach((value, index) => {
const cell = document.createElement("div");
cell.className = "cell";
cell.textContent = value;
cell.addEventListener("click", () => handleCellClick(index));
boardElement.appendChild(cell);
});
}
// Function to handle a cell click
function handleCellClick(index) {
if (board[index] === "" && !checkWinner()) {
board[index] = currentPlayer;
renderBoard();
togglePlayer();
checkWinner();
}
}
// Function to toggle between players (X and O)
function togglePlayer() {
currentPlayer = currentPlayer === "X" ? "O" : "X";
}
// Function to check for a winner
function checkWinner() {
const winPatterns = [
[0, 1, 2], [3, 4, 5], [6, 7, 8], // Rows
[0, 3, 6], [1, 4, 7], [2, 5, 8], // Columns
[0, 4, 8], [2, 4, 6] // Diagonals
];
for (const pattern of winPatterns) {
const [a, b, c] = pattern;
if (board[a] && board[a] === board[b] && board[a] === board[c]) {
alert(`Player ${currentPlayer} wins!`);
resetGame();
return true;
}
}
if (board.every(cell => cell !== "")) {
alert("It's a draw!");
resetGame();
}
return false;
}
// Function to reset the game
function resetGame() {
board = ["", "", "", "", "", "", "", "", ""];
currentPlayer = "X";
renderBoard();
}
// Initial rendering of the game board
renderBoard();
</script>
</body>
</html>
Explanation:
- The HTML structure includes a simple grid layout for the game board and a basic style for cells.
- JavaScript code initializes the game board and handles user clicks, rendering the board dynamically.
- The
renderBoardfunction creates HTML elements for each cell and updates the board’s appearance. handleCellClickfunction updates the board when a cell is clicked, toggles players, and checks for a winner.togglePlayerswitches between “X” and “O” players.checkWinnerchecks for winning patterns (rows, columns, diagonals) and declares a winner or a draw.resetGameresets the board and player to start a new game.- The script initially renders the game board.
Output:

3. JavaScript To – Do List
Let’s get started by setting up our project. This step is all about laying the groundwork for our JavaScript To-Do List app.
We’ll create the necessary files and organize our workspace. Follow these steps, and you’ll have a solid foundation for your project.
i. Establish a Project Directory
To start off, let’s maintain organization. Craft a new directory on your system to house all project files cohesively. Opt for a name such as “to-do-list-app.”
ii. Set Up Essential Files
Within the project directory, initiate three pivotal files:
index.html: The primary HTML file for the project.style.css: A CSS file containing styling rules to enhance the visual appeal of your To-Do List.script.js: The JavaScript file where the functionality of your To-Do List comes to life.
Utilize a code editor like VSCode or Sublime Text, or a simple text editor like Notepad, ensuring proper file extensions upon saving.
iii. Establish Connections Between CSS and JavaScript
After creating these files, establish connections. Open your index.html file and integrate the following code lines within the <head> tag for CSS linking:
<link rel="stylesheet" href="style.css">
And right before the closing </body> tag, add this line for the JavaScript:
<script src="script.js"></script>
These directives guide your HTML file to locate the CSS and JavaScript files and integrate them seamlessly into your webpage.
iv. Preview Your Project in a Browser
Now, let’s see the initial results. Open your index.html file in a web browser. Although you’ll encounter a blank page for now, that’s about to evolve. If the page opens without errors, you’re on the right track!
v. Set Up Your Work Environment
As you progress through the subsequent steps, maintain an open view of your code editor and web browser side by side. This setup enables real-time visualization of code modifications in the browser.
Congratulations! Your project is now configured, and you’re poised for the exciting phase. Proceed to Step 2, where we’ll commence crafting the HTML structure.
Step 2: Constructing the To-Do List Structure with HTML
With the project primed, attention turns to shaping the HTML structure of the To-Do List app.
In this phase, the focus is on scripting the essential HTML for an intuitive interface dedicated to task management. Let’s delve into the specifics.
i. Establish the Foundational HTML Structure
Open your index.html file, and commence by ensuring the fundamental structure of an HTML document is in place. For a quick refresher, the starting point should resemble the following:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>To-Do List App</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<!-- To-Do List will be added here -->
<script src="script.js"></script>
</body>
</html>
ii. Adding the To-Do List Components
Inside the <body> tag, we’ll create the components for our To-Do List app. Here’s a simple way to structure it:
<div id="todo-app">
<h1>My To-Do List</h1>
<form id="todo-form">
<input type="text" id="todo-input" placeholder="Add a new task...">
<button type="submit">Add Task</button>
</form>
<ul id="todo-list">
<!-- Tasks will be added here -->
</ul>
</div>
These directives guide your HTML file to locate the CSS and JavaScript files and integrate them seamlessly into your webpage.
iv. Preview Your Project in a Browser
Now, let’s see the initial results. Open your index.html file in a web browser. Although you’ll encounter a blank page for now, that’s about to evolve. If the page opens without errors, you’re on the right track!
v. Set Up Your Work Environment
As you progress through the subsequent steps, maintain an open view of your code editor and web browser side by side. This setup enables real-time visualization of code modifications in the browser.
Congratulations! Your project is now configured, and you’re poised for the exciting phase. Proceed to Step 2, where we’ll commence crafting the HTML structure.
Step 2: Constructing the To-Do List Structure with HTML
With the project primed, attention turns to shaping the HTML structure of the To-Do List app.
In this phase, the focus is on scripting the essential HTML for an intuitive interface dedicated to task management. Let’s delve into the specifics.
i. Establish the Foundational HTML Structure
Open your index.html file, and commence by ensuring the fundamental structure of an HTML document is in place. For a quick refresher, the starting point should resemble the following:
Step 3: Enhancing the To-Do List Appearance Using CSS
Now that our To-Do List has a solid HTML structure, the next phase involves elevating its visual aesthetics through the application of CSS.
This step aims to evolve our basic layout into a visually pleasing and user-friendly interface. Let’s infuse some creativity into our To-Do List!
i. Commence with Foundational Styles
Initiate the process by accessing your style.css file. Here, we’ll establish foundational styles to guarantee that our To-Do List exhibits an appealing appearance across various devices:
body {
font-family: 'Arial', sans-serif;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background: linear-gradient(to right, #6DD5FA, #FF758C);
color: #333;
}
#todo-app {
width: 80%;
max-width: 400px;
margin: 0 auto;
padding: 20px;
background-color: #fff;
border-radius: 10px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
Style input Button
#todo-form input[type="text"] {
width: 70%;
padding: 10px;
border: 2px solid #ddd;
border-radius: 4px;
margin-right: 10px;
}
#todo-form button {
padding: 10px 20px;
background-color: #5F9EA0;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
transition: background-color 0.3s;
}
#todo-form button:hover {
background-color: #4682B4;
}
Style to do list
#todo-list {
list-style: none;
padding: 0;
}
#todo-list li {
background-color: #f9f9f9;
margin-top: 10px;
padding: 10px;
border-radius: 4px;
display: flex;
justify-content: space-between;
align-items: center;
}
Javascript
const todoForm = document.getElementById('todo-form');
const todoInput = document.getElementById('todo-input');
const todoList = document.getElementById('todo-list');
todoForm.addEventListener('submit', function(event) {
event.preventDefault();
const newTask = todoInput.value;
if (newTask === '') {
alert('Please enter a task!');
return;
}
// Additional code to add the task will go here
todoInput.value = ''; // Clear the input field after adding a task
});
function addTask(task) {
const listItem = document.createElement('li');
listItem.textContent = task;
// Additional functionality to be added here
todoList.appendChild(listItem);
}
todoForm.addEventListener('submit', function(event) {
// Existing code
addTask(newTask); // Add the new task
});
4. JavaScript Virtual Drum kit
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body {
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
}
button {
width: 80px;
height: 80px;
font-size: 1.5em;
margin: 5px;
cursor: pointer;
}
</style>
</head>
<body>
<button data-key="65">A</button>
<button data-key="83">S</button>
<button data-key="68">D</button>
<button data-key="70">F</button>
<button data-key="71">G</button>
<button data-key="72">H</button>
<button data-key="74">J</button>
<button data-key="75">K</button>
<button data-key="76">L</button>
<script>
// Function to play a sound
function playSound(e) {
const audio = document.querySelector(`audio[data-key="${e.keyCode}"]`);
const button = document.querySelector(`button[data-key="${e.keyCode}"]`);
if (!audio) return; // Stop the function if there is no audio element
audio.currentTime = 0; // Rewind the audio to the start to allow rapid key presses
audio.play();
button.classList.add('playing'); // Add a 'playing' class for styling
}
// Function to remove the 'playing' class after the transition ends
function removeTransition(e) {
if (e.propertyName !== 'transform') return; // Skip if it's not a transform-related property
this.classList.remove('playing');
}
// Event listener to trigger playSound function on keydown
window.addEventListener('keydown', playSound);
// Event listeners to trigger removeTransition function when transition ends for each button
const buttons = document.querySelectorAll('button');
buttons.forEach(button => button.addEventListener('transitionend', removeTransition));
</script>
<!-- Audio files for each drum sound -->
<audio data-key="65" src="sounds/clap.wav"></audio>
<audio data-key="83" src="sounds/hihat.wav"></audio>
<audio data-key="68" src="sounds/kick.wav"></audio>
<audio data-key="70" src="sounds/openhat.wav"></audio>
<audio data-key="71" src="sounds/boom.wav"></audio>
<audio data-key="72" src="sounds/ride.wav"></audio>
<audio data-key="74" src="sounds/snare.wav"></audio>
<audio data-key="75" src="sounds/tom.wav"></audio>
<audio data-key="76" src="sounds/tink.wav"></audio>
</body>
</html>
Explanation:
- HTML Structure:
- Nine buttons with corresponding data-key attributes (A, S, D, F, G, H, J, K, L) for keyboard keys.
- Audio elements with data-key attributes and source (src) pointing to different drum sound files.
- CSS Styling:
- Basic styling for the body and buttons to center them on the page.
- JavaScript Code:
playSoundfunction plays the audio corresponding to the pressed key and adds a ‘playing’ class for styling.removeTransitionfunction removes the ‘playing’ class after the transition ends.- Event listener for keydown triggers
playSound. - Event listeners for transitionend on each button trigger
removeTransition.
- Audio Files:
- Nine audio files, each corresponding to a different drum sound.
This code creates a simple drum kit where pressing the specified keys triggers drum sounds with corresponding visual effects.
5. JavaScript Calculator
Lets see the code first and then see each line expalantion
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body {
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
background-color: #282c34;
color: white;
font-family: 'Arial', sans-serif;
}
#calculator {
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-gap: 10px;
max-width: 400px;
margin: auto;
padding: 20px;
background-color: #1f232a;
border-radius: 10px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
button {
width: 100%;
padding: 15px;
font-size: 1.5em;
background-color: #61dafb;
color: #282c34;
border: none;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s;
}
button:hover {
background-color: #4fa3d1;
}
#display {
grid-column: span 4;
margin: 10px 0;
padding: 10px;
font-size: 2em;
text-align: right;
background-color: #1f232a;
border: none;
border-radius: 5px;
color: #61dafb;
}
</style>
</head>
<body>
<div id="calculator">
<div id="display">0</div>
<button onclick="clearDisplay()">C</button>
<button onclick="appendToDisplay('/')">/</button>
<button onclick="appendToDisplay('*')">*</button>
<button onclick="appendToDisplay('7')">7</button>
<button onclick="appendToDisplay('8')">8</button>
<button onclick="appendToDisplay('9')">9</button>
<button onclick="appendToDisplay('-')">-</button>
<button onclick="appendToDisplay('4')">4</button>
<button onclick="appendToDisplay('5')">5</button>
<button onclick="appendToDisplay('6')">6</button>
<button onclick="appendToDisplay('+')">+</button>
<button onclick="appendToDisplay('1')">1</button>
<button onclick="appendToDisplay('2')">2</button>
<button onclick="appendToDisplay('3')">3</button>
<button onclick="calculateResult()">=</button>
<button onclick="appendToDisplay('0')">0</button>
<button onclick="appendToDisplay('.')">.</button>
</div>
<script>
let displayValue = '0';
function updateDisplay() {
document.getElementById('display').innerText = displayValue;
}
function appendToDisplay(value) {
if (displayValue === '0' && value !== '.') {
displayValue = value;
} else {
displayValue += value;
}
updateDisplay();
}
function clearDisplay() {
displayValue = '0';
updateDisplay();
}
function calculateResult() {
try {
displayValue = eval(displayValue).toString();
} catch (error) {
displayValue = 'Error';
}
updateDisplay();
}
</script>
</body>
</html>
Output:
Lets break down and understand each part of the code:
Document Type Declaration and HTML Start:
<!DOCTYPE html>
<html lang="en">
<!DOCTYPE html>declares the document type and version of HTML being used.<html lang="en">starts the HTML document with the specified language attribute as English.
Head Section:
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="UTF-8">sets the character encoding to UTF-8.<meta name="viewport" content="width=device-width, initial-scale=1.0">configures the viewport for responsive design.
CSS Styling:
<style>
body {
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
background-color: #282c34;
color: white;
font-family: 'Arial', sans-serif;
}
/* ... other styles for calculator, buttons, and display ... */
</style>
- Defines styles for the body, calculator, buttons, and display using Flexbox and Grid layout.
- Applies a dark background color, white text, and specific fonts.
Body Section:
<body>
<div id="calculator">
<!-- ... calculator buttons and display ... -->
</div>
</body>
Contains the calculator within a div with the ID ‘calculator’.
Calculator Structure and Buttons:
<div id="calculator">
<div id="display">0</div>
<button onclick="clearDisplay()">C</button>
<!-- ... other buttons ... -->
</div>
- Sets up the calculator grid structure with a display div and buttons.
- Each button has an
onclickattribute calling specific JavaScript functions.
JavaScript code breakdown
let displayValue = '0';
Declares a variable displayValue and initializes it with the value ‘0’. This variable represents the current value displayed on the calculator.
function updateDisplay() {
document.getElementById('display').innerText = displayValue;
}
Defines a function updateDisplay that updates the content of the HTML element with the ID ‘display’ to the current value of displayValue. This function is responsible for visually updating the calculator display.
function appendToDisplay(value) {
if (displayValue === '0' && value !== '.') {
displayValue = value;
} else {
displayValue += value;
}
updateDisplay();
}
Defines a function appendToDisplay that appends a specified value to the current displayValue. It checks if the current display value is ‘0’ and the incoming value is not a dot (‘.’) before updating. This helps avoid leading zeros and consecutive dots in the display.
function clearDisplay() {
displayValue = '0';
updateDisplay();
}
Defines a function clearDisplay that resets the displayValue to ‘0’ and updates the display accordingly.
function calculateResult() {
try {
displayValue = eval(displayValue).toString();
} catch (error) {
displayValue = 'Error';
}
updateDisplay();
}
Defines a function calculate Result that attempts to evaluate the mathematical expression represented by display Value using the eval function. If successful, it converts the result to a string. If an error occurs during evaluation, it sets display Value to ‘Error’. The display is then updated using the update Display function.
These JavaScript functions collectively handle the core logic of the calculator, including updating the display, appending values, clearing the display, and calculating results. The try…catch block ensures that any errors during evaluation are caught and handled gracefully.
6. JavaScript Hangman Game
Source Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body {
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
background-color: #282c34;
color: white;
font-family: 'Arial', sans-serif;
}
#hangman-container {
display: flex;
flex-direction: column;
align-items: center;
text-align: center;
}
#word-display {
font-size: 2em;
margin: 20px 0;
}
#keyboard {
display: grid;
grid-template-columns: repeat(7, 1fr);
grid-gap: 10px;
max-width: 300px;
margin: 20px 0;
}
button {
width: 100%;
padding: 10px;
font-size: 1.5em;
background-color: #61dafb;
color: #282c34;
border: none;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s;
}
button:hover {
background-color: #4fa3d1;
}
</style>
</head>
<body>
<div id="hangman-container">
<div id="word-display"></div>
<div id="keyboard"></div>
</div>
<script>
// Hangman Game Logic
const words = ['javascript', 'hangman', 'developer', 'coding', 'programming'];
let selectedWord = words[Math.floor(Math.random() * words.length)];
let guessedLetters = new Set();
let remainingAttempts = 6;
function initializeGame() {
createKeyboard();
updateWordDisplay();
}
function createKeyboard() {
const keyboardContainer = document.getElementById('keyboard');
for (let letter of 'abcdefghijklmnopqrstuvwxyz') {
const button = document.createElement('button');
button.innerText = letter;
button.onclick = () => handleGuess(letter);
keyboardContainer.appendChild(button);
}
}
function updateWordDisplay() {
const wordDisplay = document.getElementById('word-display');
wordDisplay.innerHTML = selectedWord
.split('')
.map(letter => guessedLetters.has(letter) ? letter : '_')
.join(' ');
}
function handleGuess(letter) {
guessedLetters.add(letter);
if (!selectedWord.includes(letter)) {
remainingAttempts--;
}
updateWordDisplay();
checkGameStatus();
}
function checkGameStatus() {
if (remainingAttempts === 0) {
alert('Game Over! The word was: ' + selectedWord);
resetGame();
} else if (!document.getElementById('word-display').innerText.includes('_')) {
alert('Congratulations! You guessed the word: ' + selectedWord);
resetGame();
}
}
function resetGame() {
selectedWord = words[Math.floor(Math.random() * words.length)];
guessedLetters.clear();
remainingAttempts = 6;
createKeyboard();
updateWordDisplay();
}
// Initialize the game
initializeGame();
</script>
</body>
</html>
Explanation:
HTML Structure:
The HTML structure is standard, including a head with metadata and a body containing a hangman game container.
CSS Styles:
CSS styles are provided for the body, hangman container, word display, keyboard, and buttons to create a visually appealing layout.
JavaScript Logic:
- An array words contains words for the hangman game.
- initializeGame sets up the initial state of the game, calling
- createKeyboard and updateWordDisplay.
- createKeyboard dynamically generates clickable buttons for each letter in the alphabet.
- updateWordDisplay updates the displayed word based on guessed letters.
- handleGuess processes user guesses, updates the display, and checks the game status.
- checkGameStatus alerts the user if the game is won or lost.
resetGame resets the game for a new round. - The game initializes on page load by calling initializeGame().
7. JavaScript Weather App
In this tutorial, we’ll build a straightforward Weather App using JavaScript and the OpenWeatherMap API. This app will allow users to check the current weather conditions for a specific location.
Prerequisites
- OpenWeatherMap API Key – You’ll need to sign up for a free API key to access weather data.
HTML Structure
Let’s start with the HTML structure for our Weather App:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Weather App</title>
</head>
<body>
<div class="container">
<input type="text" id="cityInput" placeholder="Enter City">
<button onclick="getWeather()">Get Weather</button>
<div id="weatherInfo"></div>
</div>
<script src="script.js"></script>
</body>
</html>
CSS Styles (style.css)
Add some basic styles to make the app visually appealing:
body {
font-family: 'Arial', sans-serif;
background-color: #f0f0f0;
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
}
.container {
text-align: center;
padding: 20px;
background-color: #fff;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
border-radius: 5px;
}
input {
padding: 10px;
margin-right: 10px;
}
button {
padding: 10px;
background-color: #3498db;
color: #fff;
border: none;
cursor: pointer;
border-radius: 5px;
}
button:hover {
background-color: #2980b9;
}
#weatherInfo {
margin-top: 20px;
font-size: 1.2em;
}
JavaScript Logic (script.js)
Now, let’s implement the JavaScript logic to interact with the OpenWeatherMap API and display weather information:
function getWeather() {
const cityInput = document.getElementById('cityInput').value;
if (cityInput.trim() === '') {
alert('Please enter a city');
return;
}
const apiKey = 'YOUR_API_KEY'; // Replace with your OpenWeatherMap API key
const apiUrl = `https://api.openweathermap.org/data/2.5/weather?q=${cityInput}&appid=${apiKey}&units=metric`;
fetch(apiUrl)
.then(response => response.json())
.then(data => {
displayWeather(data);
})
.catch(error => {
console.error('Error fetching weather data:', error);
alert('Error fetching weather data. Please try again.');
});
}
function displayWeather(data) {
const weatherInfo = document.getElementById('weatherInfo');
const cityName = data.name;
const temperature = data.main.temp;
const description = data.weather[0].description;
const weatherHTML = `
<h2>${cityName}</h2>
<p>Temperature: ${temperature}°C</p>
<p>Description: ${description}</p>
`;
weatherInfo.innerHTML = weatherHTML;
}
Explanation

- HTML Structure:
- The HTML contains input for entering the city, a button to fetch weather data, and a container for displaying weather information.
- CSS Styles:
- Provides basic styling to improve the app’s appearance.
- JavaScript Logic:
getWeatherfunction is called when the user clicks the “Get Weather” button.- The OpenWeatherMap API is queried based on the entered city.
- The fetched data is processed and displayed using the
displayWeatherfunction.
- API Key:
- Replace
'YOUR_API_KEY'with the API key obtained from OpenWeatherMap.
- Replace
- Display Weather:
- Weather information (city name, temperature, and description) is displayed in the
#weatherInfodiv.
- Weather information (city name, temperature, and description) is displayed in the
Conclusion
This simple Weather App allows users to check the current weather by entering a city. It serves as a starting point for more advanced features and improvements. Explore the OpenWeatherMap API documentation for additional functionalities.
8. JavaScript Form Validation
Comprehensive JavaScript code for form validation along with explanations for each line of code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Validation</title>
<style>
body {
font-family: 'Arial', sans-serif;
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
}
form {
text-align: center;
padding: 20px;
background-color: #fff;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
border-radius: 5px;
}
input {
padding: 10px;
margin-bottom: 10px;
width: 100%;
box-sizing: border-box;
}
button {
padding: 10px;
background-color: #3498db;
color: #fff;
border: none;
cursor: pointer;
border-radius: 5px;
}
button:hover {
background-color: #2980b9;
}
.error-message {
color: red;
margin-top: -10px;
margin-bottom: 10px;
}
</style>
</head>
<body>
<form onsubmit="validateForm(event)">
<input type="text" id="fullName" placeholder="Full Name">
<div id="fullNameError" class="error-message"></div>
<input type="email" id="email" placeholder="Email">
<div id="emailError" class="error-message"></div>
<input type="password" id="password" placeholder="Password">
<div id="passwordError" class="error-message"></div>
<button type="submit">Submit</button>
</form>
<script>
function validateForm(event) {
event.preventDefault(); // Prevents the form from submitting normally
// Fetch input values
const fullName = document.getElementById('fullName').value;
const email = document.getElementById('email').value;
const password = document.getElementById('password').value;
// Reset error messages
document.getElementById('fullNameError').innerText = '';
document.getElementById('emailError').innerText = '';
document.getElementById('passwordError').innerText = '';
// Validate Full Name
if (!fullName.trim()) {
document.getElementById('fullNameError').innerText = 'Full Name is required';
}
// Validate Email
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email)) {
document.getElementById('emailError').innerText = 'Enter a valid email address';
}
// Validate Password
if (password.length < 6) {
document.getElementById('passwordError').innerText = 'Password must be at least 6 characters';
}
// If all validations pass, you can submit the form or perform other actions
if (!document.querySelectorAll('.error-message').length) {
alert('Form submitted successfully!');
// Here you can submit the form using AJAX or any other desired action
}
}
</script>
</body>
</html>
JavaScript code Break Down:
function validateForm(event) {
event.preventDefault(); // Prevents the form from submitting normally
// Fetch input values
const fullName = document.getElementById('fullName').value;
const email = document.getElementById('email').value;
const password = document.getElementById('password').value;
// Reset error messages
document.getElementById('fullNameError').innerText = '';
document.getElementById('emailError').innerText = '';
document.getElementById('passwordError').innerText = '';
// Validate Full Name
if (!fullName.trim()) {
document.getElementById('fullNameError').innerText = 'Full Name is required';
}
// Validate Email
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email)) {
document.getElementById('emailError').innerText = 'Enter a valid email address';
}
// Validate Password
if (password.length < 6) {
document.getElementById('passwordError').innerText = 'Password must be at least 6 characters';
}
// If all validations pass, you can submit the form or perform other actions
if (!document.querySelectorAll('.error-message').length) {
alert('Form submitted successfully!');
// Here you can submit the form using AJAX or any other desired action
}
}
Explanation:
function validateForm(event)
Declares a function named validateForm that takes an event parameter.
event.preventDefault();
Prevents the form from submitting normally, allowing custom validation logic.
Fetching Input Values:
const fullName = document.getElementById(‘fullName’).value;
const email = document.getElementById(’email’).value;
const password = document.getElementById(‘password’).value;
Retrieves values from Full Name, Email, and Password input fields.
Resetting Error Messages:
document.getElementById(‘fullNameError’).innerText = ”;
document.getElementById(’emailError’).innerText = ”;
document.getElementById(‘passwordError’).innerText = ”;
Clears any previous error messages.
Validation for Full Name:
if (!fullName.trim()) { document.getElementById(‘fullNameError’).innerText = ‘Full Name is required’; }
Checks if Full Name is empty and displays an error message if true.
Validation for Email:
const emailRegex = /^[^\s@]+@[^\s@]+.[^\s@]+$/;
Defines a regular expression for a valid email format.
if (!emailRegex.test(email)) { document.getElementById(’emailError’).innerText = ‘Enter a valid email address’; }
Checks if the entered email matches the regular expression.
Validation for Password:
if (password.length < 6) { document.getElementById(‘passwordError’).innerText = ‘Password must be at least 6 characters’; }
Checks if the password is less than 6 characters.
Final Check and Submission:
if (!document.querySelectorAll(‘.error-message’).length) { alert(‘Form submitted successfully!’); }
Alerts success if no error messages are present.
You can customize this part to submit the form using AJAX or other actions.





Leave a Reply