10 Fun JavaScript Coding Projects to Learn JavaScript code with Source Code and Downloadable PDF Guide

JavaScript Fun coding Projects

Guess the Number Game – Random Quote Generator – Typing Speed Test – Infinite Scrolling – Drag and Drop – Password Strength Meter – Dynamic Table Generator – Drag and Drop File Uploader – Stopwatch – Rock-Paper-Scissors Game

Guess the Number Game

This game allows users to guess a random number between 1 and 100. Here’s how to build it:

// Generate a random number between 1 and 100

const secretNumber = Math.floor(Math.random() * 100) + 1;

// Keep track of the number of guesses

let numGuesses = 0;

// Prompt the user to guess a number

let guess = parseInt(prompt(“Guess a number between 1 and 100”));

// While the guess is not correct

while (guess !== secretNumber) {

  // Increment the number of guesses

  numGuesses++;

  // Provide a hint to the user

  if (guess < secretNumber) {

    guess = parseInt(prompt(“Too low. Guess again.”));

  } else {

    guess = parseInt(prompt(“Too high. Guess again.”));

  }

}

// The user has guessed the correct number

alert(`You win! It took you ${numGuesses} guesses.`);

In this example, we generate a random number between 1 and 100 using Math.random() and Math.floor(). We then use a while loop to prompt the user to guess a number until they guess the correct number. We keep track of the number of guesses using a numGuesses variable and provide hints to the user if their guess is too high or too low. Once the user has guessed the correct number, we display a message indicating how many guesses it took them to win.

Random Quote Generator

This script displays a random quote each time the user clicks a button. Here’s how to build it:

// Array of quotes

const quotes = [

  “The greatest glory in living lies not in never falling, but in rising every time we fall. -Nelson Mandela”,

  “The way to get started is to quit talking and begin doing. -Walt Disney”,

  “Your time is limited, don’t waste it living someone else’s life. -Steve Jobs”,

  “If life were predictable it would cease to be life, and be without flavor. -Eleanor Roosevelt”,

  “If you look at what you have in life, you’ll always have more. If you look at what you don’t have in life, you’ll never have enough. -Oprah Winfrey”,

  “If you set your goals ridiculously high and it’s a failure, you will fail above everyone else’s success. -James Cameron”

];

// Function to generate a random quote

function getRandomQuote() {

  const randomIndex = Math.floor(Math.random() * quotes.length);

  return quotes[randomIndex];

}

// Event listener for button click

const button = document.querySelector(“button”);

button.addEventListener(“click”, function() {

  const quote = getRandomQuote();

  document.querySelector(“#quote”).textContent = quote;

});

In this example, we create an array of quotes and a function getRandomQuote() that returns a random quote from the array. We add an event listener to a button that, when clicked, generates a random quote and displays it on the page.

Typing Speed Test

This script tests the user’s typing speed by measuring how long it takes them to type a random sentence. Here’s how to build it:

// Array of sentences for typing test

const sentences = [

  “The quick brown fox jumps over the lazy dog.”,

  “The only way to do great work is to love what you do.”,

  “Believe in yourself and all that you are. Know that there is something inside you that is greater than any obstacle.”,

  “Success is not final, failure is not fatal: it is the courage to continue that counts.”,

  “The best way to predict the future is to invent it.”,

  “The only person you are destined to become is the person you decide to be.”

];

// Function to generate a random sentence

function getRandomSentence() {

  const randomIndex = Math.floor(Math.random() * sentences.length);

  return sentences[randomIndex];

}

// Variables for tracking the typing test

let startTime, endTime;

// Event listener for typing test start

const startButton = document.querySelector(“#start”);

startButton.addEventListener(“click”, function() {

  // Display a random sentence

  const sentence = getRandomSentence();

  document.querySelector(“#sentence”).textContent = sentence;

  // Enable the text input and set focus

  const input = document.querySelector(“#input”);

  input.disabled = false;

  input.focus();

  // Record the start time

  startTime = new Date();

});

// Event listener for typing test end

const endButton = document.querySelector(“#end”);

endButton.addEventListener(“click”, function() {

  // Disable the text input

  const input = document.querySelector(“#input”);

  input.disabled = true;

  // Record the end time

  endTime = new Date();

  // Calculate the typing speed

  const timeDiff = endTime – startTime;

  const seconds = timeDiff / 1000;

  const numWords = document.querySelector(“#sentence”).textContent.split(” “).length;

  const wordsPerMinute = Math.round(numWords / seconds * 60);

  // Display the typing speed

  document.querySelector(“#speed”).textContent = wordsPerMinute;

});

In this example, we create an array of sentences for the typing test and a function getRandomSentence() that returns a random sentence from the array. We add event listeners to two buttons, one to start the test and one to end it. When the user clicks the start button, we display a random sentence, enable the text input, and record the start time. When the user clicks the end button, we disable the text input, record the end time, calculate the typing speed, and display it on the page. The typing speed is calculated by dividing the number of words in the sentence by the time it took to type the sentence, then multiplying by 60 to get words per minute.

Infinite Scrolling

This example demonstrates how to implement infinite scrolling using JavaScript. We have a container element with a fixed height and overflow set to auto. When the user scrolls to the bottom of the container, we load more content and append it to the container.

// Get the container element

const container = document.querySelector(“#container”);

// Initialize the counter and load the first set of items

let counter = 0;

loadItems();

// Add a scroll event listener to the container

container.addEventListener(“scroll”, function() {

  if (container.scrollTop + container.clientHeight >= container.scrollHeight) {

    // User has scrolled to the bottom, load more items

    loadItems();

  }

});

// Function to load more items

function loadItems() {

  for (let i = 0; i < 10; i++) {

    // Create a new item and append it to the container

    const item = document.createElement(“div”);

    item.textContent = `Item ${counter++}`;

    container.appendChild(item);

  }

}

In this example, we first get the container element and initialize the counter to 0. We then load the first set of items using the loadItems() function. We add a scroll event listener to the container that checks if the user has scrolled to the bottom of the container. If they have, we call the loadItems() function to load more items. The loadItems() function creates 10 new items and appends them to the container, incrementing the counter for each item.

Drag and Drop

This example demonstrates how to implement drag and drop using JavaScript. We have a list of items that can be dragged and dropped to rearrange their order. We use the HTML5 Drag and Drop API to implement the functionality.

// Get the list and all list items

const list = document.querySelector(“#list”);

const items = document.querySelectorAll(“li”);

// Add a dragstart event listener to each item

items.forEach(function(item) {

  item.addEventListener(“dragstart”, function(event) {

    // Set the data and the effect on the drag event

    event.dataTransfer.setData(“text/plain”, item.textContent);

    event.dataTransfer.effectAllowed = “move”;

  });

});

// Add a dragover event listener to the list

list.addEventListener(“dragover”, function(event) {

  // Prevent the default behavior and set the drop effect

  event.preventDefault();

  event.dataTransfer.dropEffect = “move”;

});

// Add a drop event listener to the list

list.addEventListener(“drop”, function(event) {

  // Prevent the default behavior and get the data

  event.preventDefault();

  const data = event.dataTransfer.getData(“text/plain”);

  // Find the target item and insert the dropped item before it

  const target = event.target.closest(“li”);

  const item = document.createElement(“li”);

  item.textContent = data;

  list.insertBefore(item, target);

});

In this example, we first get the list and all list items. We add a dragstart event listener to each item that sets the data and effect on the drag event. We then add a dragover event listener to the list that prevents the default behavior and sets the drop effect. Finally, we add a drop event listener to the list that prevents the default behavior, gets the data, finds the target item, and inserts the dropped item before it.

Password Strength Meter

This example demonstrates how to implement a password strength meter using JavaScript. We have a password input field and a meter element that shows the strength of the password. The strength is determined by the length of the password and variation of the case of the letters, use of numbers, and symbols and how many times a character is repeated.

// Get the password input and strength meter elements

const passwordInput = document.querySelector(“#password”);

const strengthMeter = document.querySelector(“#strength-meter”);

// Add an input event listener to the password input

passwordInput.addEventListener(“input”, function() {

  const password = passwordInput.value;

  const strength = calculatePasswordStrength(password);

  // Update the strength meter element

  strengthMeter.value = strength;

  strengthMeter.style.backgroundColor = getStrengthColor(strength);

});

// Function to calculate the strength of a password

function calculatePasswordStrength(password) {

  let strength = 0;

  // Add points for password length

  strength += password.length * 4;

  // Add points for uppercase letters

  if (/[A-Z]/.test(password)) {

    strength += 5;

  }

  // Add points for lowercase letters

  if (/[a-z]/.test(password)) {

    strength += 5;

  }

  // Add points for numbers

  if (/\d/.test(password)) {

    strength += 5;

  }

  // Add points for symbols

  if (/[^\w\s]/.test(password)) {

    strength += 5;

  }

  // Subtract points for consecutive repeating characters

  if (/([a-zA-Z])\1/.test(password)) {

    strength -= 10;

  }

  return Math.max(0, Math.min(100, strength));

}

// Function to get the color for a strength value

function getStrengthColor(strength) {

  if (strength <= 25) {

    return “red”;

  } else if (strength <= 50) {

    return “orange”;

  } else if (strength <= 75) {

    return “yellow”;

  } else {

    return “green”;

  }

}

In this example, we first get the password input and strength meter elements. We add an input event listener to the password input that calculates the strength of the password using the calculatePasswordStrength() function and updates the strength meter element with the result.

The calculatePasswordStrength() function takes a password as input and calculates its strength based on various criteria. We add points for the length of the password, uppercase and lowercase letters, numbers, and symbols. We also subtract points for consecutive repeating characters. The strength is then clamped to a value between 0 and 100.

The getStrengthColor() function takes a strength value as input and returns a color based on its range. A strength value of 0-25 is red, 26-50 is orange, 51-75 is yellow, and 76-100 is green.

Together, these functions implement a simple password strength meter that updates in real time as the user types in their password.

Dynamic Table Generator

const table = document.createElement(‘table’);

const tbody = document.createElement(‘tbody’);

const rows = 5;

const cols = 5;

for (let i = 0; i < rows; i++) {

  const row = document.createElement(‘tr’);

  for (let j = 0; j < cols; j++) {

    const cell = document.createElement(‘td’);

    cell.textContent = `Row ${i + 1}, Column ${j + 1}`;

    row.appendChild(cell);

  }

  tbody.appendChild(row);

}

table.appendChild(tbody);

document.body.appendChild(table);

This code generates a dynamic table with 5 rows and 5 columns. We first create a table and tbody element using createElement(), then use two nested for loops to create the rows and columns. For each cell, we set the text content to the row and column number, and append it to the current row. Finally, we append the tbody to the table and the table to the body of the HTML document.

Drag and Drop File Uploader

const fileInput = document.querySelector(‘#file-input’);

const dropArea = document.querySelector(‘#drop-area’);

dropArea.addEventListener(‘dragover’, e => {

  e.preventDefault();

  dropArea.classList.add(‘dragging’);

});

dropArea.addEventListener(‘dragleave’, e => {

  e.preventDefault();

  dropArea.classList.remove(‘dragging’);

});

dropArea.addEventListener(‘drop’, e => {

  e.preventDefault();

  dropArea.classList.remove(‘dragging’);

  const files = e.dataTransfer.files;

  fileInput.files = files;

});

This code creates a drag and drop file uploader. We first get the file input and drop area elements using querySelector(). We add event listeners to the drop area for dragover, dragleave, and drop events. When the user drags a file over the drop area, we prevent the default behavior and add a CSS class to highlight the area. When the user leaves the drop area, we remove the CSS class. When the user drops the file, we prevent the default behavior, remove the CSS class, and set the file input’s files property to the dropped files.

Stopwatch

const stopwatchDisplay = document.querySelector(‘#stopwatch’);

let startTime;

function startStopwatch() {

  startTime = Date.now();

  setInterval(updateStopwatch, 10);

}

function updateStopwatch() {

  const elapsed = Date.now() – startTime;

  const minutes = Math.floor(elapsed / 60000);

  const seconds = Math.floor((elapsed % 60000) / 1000);

  const milliseconds = elapsed % 1000;

  stopwatchDisplay.textContent = `${minutes.toString().padStart(2, ‘0’)}:${seconds.toString().padStart(2, ‘0’)}.${milliseconds.toString().padStart(3, ‘0’)}`;

}

function stopStopwatch() {

  clearInterval(updateStopwatch);

}

startStopwatch();

This code creates a stopwatch that displays the elapsed time in minutes, seconds, and milliseconds. We first get the stopwatch display element using querySelector(). We define three functions: startStopwatch(), updateStopwatch(), and stopStopwatch(). startStopwatch() sets the start time using Date.now() and starts a timer using setInterval(). The timer calls updateStopwatch() every 10 milliseconds. updateStopwatch() calculates the elapsed time using Date.now() – startTime, and formats it as a string in minutes, seconds, and milliseconds. We use padStart()

Rock-Paper-Scissors Game

const choices = [‘rock’, ‘paper’, ‘scissors’];

function playRound(playerChoice) {

  const computerChoice = choices[Math.floor(Math.random() * choices.length)];

  let result = ”;

  if (playerChoice === computerChoice) {

    result = ‘Tie!’;

  } else if ((playerChoice === ‘rock’ && computerChoice === ‘scissors’) ||

             (playerChoice === ‘paper’ && computerChoice === ‘rock’) ||

             (playerChoice === ‘scissors’ && computerChoice === ‘paper’)) {

    result = ‘You win!’;

  } else {

    result = ‘Computer wins!’;

  }

  return `You chose ${playerChoice}, computer chose ${computerChoice}. ${result}`;

}

console.log(playRound(‘rock’)); // Example output: “You chose rock, computer chose scissors. You win!”

This code implements a simple game of rock-paper-scissors. We start by defining an array of the three choices. We define a function playRound(playerChoice) that takes the player’s choice as an argument. Inside the function, we randomly select the computer’s choice using Math.floor(Math.random() * choices.length). We then use a series of if-else statements to determine the result of the round, based on the player’s and computer’s choices. We return a string that includes both choices and the result of the round. We can test the function by calling it with a player choice, and it will return a string with the result of that round.