Text To Speech In JavaScript

<!DOCTYPE html>
<!-- Declares this as an HTML5 document -->

<html>
<head>
  <title>Text to Speech</title>

  <style>
    body {
      font-family: Arial, sans-serif; /* Simple readable font */
      text-align: center;            /* Center everything */
      margin-top: 50px;              /* Space from top */
    }

    textarea {
      width: 300px;                  /* Text box width */
      height: 100px;                 /* Text box height */
      font-size: 16px;               /* Text size */
    }

    button {
      padding: 10px 20px;            /* Button size */
      font-size: 16px;
      cursor: pointer;
    }
  </style>
</head>

<body>

  <h1>๐Ÿ”Š Text to Speech</h1>

  <!-- Text input box -->
  <textarea id="text">
Hello! This is text to speech in JavaScript.
  </textarea>

  <br><br>

  <!-- Button to start speaking -->
  <button onclick="speakText()">Speak</button>

  <script>
    // Function that converts text to speech
    function speakText() {

      // Get the text from textarea
      let text = document.getElementById("text").value;

      // Create a speech object
      let speech = new SpeechSynthesisUtterance();

      // Assign text to the speech object
      speech.text = text;

      // Set language (English - US)
      speech.lang = "en-US";

      // Set voice speed (1 = normal)
      speech.rate = 1;

      // Set pitch (1 = normal)
      speech.pitch = 1;

      // Set volume (0 to 1)
      speech.volume = 1;

      // Speak the text
      window.speechSynthesis.speak(speech);
    }
  </script>

</body>
</html>

Action Game In JavaScript

This action game is a simple browser-based 2D game built using HTML, CSS, and JavaScript where the player controls a green square at the bottom of the screen using the left and right arrow keys to avoid falling red enemy blocks. The game area is created with HTML and styled using CSS, while JavaScript handles the game logic, including player movement, enemy creation, animation, collision detection, and scoring. Enemies are continuously generated at random horizontal positions and move downward at a fixed speed, and if an enemy collides with the player, the game stops and a game-over screen is displayed. The playerโ€™s score increases each time an enemy successfully passes off the screen without hitting the player, encouraging quick reactions and precise movement to survive as long as possible.

<!DOCTYPE html>
<html lang="en">
<head>
  <!-- Character encoding -->
  <meta charset="UTF-8" />

  <!-- Page title -->
  <title>Action Game - Avoid Enemies</title>

  <!-- Responsive layout for mobile -->
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />

  <!-- Game styling -->
  <style>
    /* Remove default margin and set background */
    body {
      margin: 0;
      background: #111;
      color: #fff;
      font-family: Arial, sans-serif;
      text-align: center;
    }

    /* Heading spacing */
    h2 {
      margin: 10px 0;
    }

    /* Main game container */
    #game {
      position: relative;          /* Needed for absolute children */
      width: 400px;
      height: 500px;
      background: #222;
      margin: 0 auto;              /* Center horizontally */
      overflow: hidden;            /* Hide enemies outside area */
      border: 3px solid #fff;
    }

    /* Player block */
    #player {
      position: absolute;
      width: 40px;
      height: 40px;
      background: lime;
      bottom: 10px;                /* Place near bottom */
      left: 180px;                 /* Start in center */
      border-radius: 6px;
    }

    /* Enemy blocks */
    .enemy {
      position: absolute;
      width: 40px;
      height: 40px;
      background: red;
      top: -40px;                  /* Start above screen */
      border-radius: 6px;
    }

    /* Game over overlay */
    #gameOver {
      display: none;               /* Hidden until game ends */
      position: absolute;
      inset: 0;                    /* Cover entire game area */
      background: rgba(0,0,0,0.8);
      color: white;
      font-size: 24px;
      align-items: center;
      justify-content: center;
      flex-direction: column;
    }

    /* Restart button */
    button {
      padding: 10px 20px;
      font-size: 16px;
      margin-top: 10px;
      cursor: pointer;
    }
  </style>
</head>
<body>

  <!-- Game title -->
  <h2>๐Ÿ”ฅ Action Game: Avoid the Enemies</h2>

  <!-- Controls info -->
  <p>Use โ—€ โ–ถ arrow keys to move</p>

  <!-- Score display -->
  <h3>Score: <span id="score">0</span></h3>

  <!-- Game area -->
  <div id="game">

    <!-- Player element -->
    <div id="player"></div>

    <!-- Game over screen -->
    <div id="gameOver">
      <div>๐Ÿ’€ Game Over</div>
      <button onclick="location.reload()">Restart</button>
    </div>
  </div>

  <!-- JavaScript game logic -->
  <script>
    // Get references to DOM elements
    const game = document.getElementById("game");
    const player = document.getElementById("player");
    const scoreDisplay = document.getElementById("score");
    const gameOverScreen = document.getElementById("gameOver");

    // Game variables
    let score = 0;                 // Player score
    let playerX = 180;             // Player horizontal position
    let gameRunning = true;        // Game state

    // Listen for keyboard input
    document.addEventListener("keydown", (e) => {
      if (!gameRunning) return;    // Stop movement if game over

      // Move left
      if (e.key === "ArrowLeft" && playerX > 0) {
        playerX -= 20;
      }

      // Move right
      if (e.key === "ArrowRight" && playerX < 360) {
        playerX += 20;
      }

      // Apply movement to player
      player.style.left = playerX + "px";
    });

    // Function to create a falling enemy
    function createEnemy() {
      if (!gameRunning) return;

      // Create enemy element
      const enemy = document.createElement("div");
      enemy.classList.add("enemy");

      // Random horizontal position
      enemy.style.left = Math.random() * 360 + "px";

      // Add enemy to game area
      game.appendChild(enemy);

      let enemyY = -40;            // Starting vertical position

      // Move enemy downward repeatedly
      const fallInterval = setInterval(() => {
        if (!gameRunning) {
          clearInterval(fallInterval);
          enemy.remove();
          return;
        }

        // Move enemy down
        enemyY += 5;
        enemy.style.top = enemyY + "px";

        // Check collision with player
        if (
          enemyY > 440 &&
          Math.abs(playerX - enemy.offsetLeft) < 40
        ) {
          gameOver();
          clearInterval(fallInterval);
        }

        // Remove enemy if it leaves screen
        if (enemyY > 500) {
          enemy.remove();
          clearInterval(fallInterval);
          score++;                 // Increase score
          scoreDisplay.textContent = score;
        }
      }, 30); // Speed of enemy fall
    }

    // Game over function
    function gameOver() {
      gameRunning = false;
      gameOverScreen.style.display = "flex";
    }

    // Create enemies repeatedly
    setInterval(createEnemy, 800);
  </script>

</body>
</html>

Snowfall in JavaScript

This single-file snowfall effect uses HTML Canvas and JavaScript to create a smooth, lightweight animation of falling snowflakes across the screen. The canvas automatically resizes to fit the browser window, while each snowflake is randomly generated with its own size, speed, and horizontal drift to simulate natural movement. The animation runs efficiently using requestAnimationFrame, continuously clearing and redrawing the scene to give the illusion of gentle snowfall. Because all HTML, CSS, and JavaScript are contained in one file, it is easy to use, customize, and deploy without any external dependencies.

<!DOCTYPE html>
<html lang="en">
<head>
  <!-- Set character encoding -->
  <meta charset="UTF-8" />

  <!-- Page title -->
  <title>Snowfall Effect</title>

  <style>
    /* Remove default spacing and make page full height */
    html, body {
      margin: 0;              /* Remove default margin */
      padding: 0;             /* Remove default padding */
      background: #0b1d3a;    /* Dark blue background (night sky) */
      overflow: hidden;       /* Prevent scrollbars */
      height: 100%;           /* Full viewport height */
    }

    /* Make canvas fill the screen */
    canvas {
      display: block;         /* Remove inline spacing */
    }
  </style>
</head>
<body>

  <!-- Canvas where snow will be drawn -->
  <canvas id="snow"></canvas>

  <script>
    // Get the canvas element by its ID
    const canvas = document.getElementById("snow");

    // Get 2D drawing context from canvas
    const ctx = canvas.getContext("2d");

    // Function to resize canvas to window size
    function resize() {
      canvas.width = window.innerWidth;   // Match window width
      canvas.height = window.innerHeight; // Match window height
    }

    // Initial resize when page loads
    resize();

    // Resize canvas whenever window size changes
    window.addEventListener("resize", resize);

    // Array to store all snowflake objects
    const snowflakes = [];

    // Total number of snowflakes
    const SNOW_COUNT = 200;

    // Create snowflake objects
    for (let i = 0; i < SNOW_COUNT; i++) {
      snowflakes.push({
        x: Math.random() * canvas.width,  // Random horizontal position
        y: Math.random() * canvas.height, // Random vertical position
        r: Math.random() * 3 + 1,          // Radius (size) of snowflake
        speed: Math.random() * 2 + 0.5,    // Falling speed
        drift: Math.random() * 0.6 - 0.3   // Horizontal movement (wind)
      });
    }

    // Main drawing function
    function draw() {
      // Clear entire canvas before redrawing
      ctx.clearRect(0, 0, canvas.width, canvas.height);

      // Set snowflake color
      ctx.fillStyle = "white";

      // Start a new drawing path
      ctx.beginPath();

      // Draw each snowflake
      for (const s of snowflakes) {
        ctx.moveTo(s.x, s.y);                 // Move drawing cursor
        ctx.arc(s.x, s.y, s.r, 0, Math.PI * 2); // Draw circular snowflake
      }

      // Fill all snowflakes with color
      ctx.fill();

      // Update snowflake positions
      update();

      // Request next animation frame (smooth animation)
      requestAnimationFrame(draw);
    }

    // Update snowflake movement
    function update() {
      for (const s of snowflakes) {
        s.y += s.speed;   // Move snowflake downward
        s.x += s.drift;   // Move snowflake sideways (wind)

        // If snowflake falls below screen, reset to top
        if (s.y > canvas.height) {
          s.y = -s.r;                         // Start above canvas
          s.x = Math.random() * canvas.width; // Random horizontal position
        }

        // Wrap snowflake horizontally
        if (s.x > canvas.width) s.x = 0;
        if (s.x < 0) s.x = canvas.width;
      }
    }

    // Start the animation loop
    draw();
  </script>

</body>
</html>

Simple Image Slider In JavaScript

<!DOCTYPE html>
<html lang="en">
<head>
  <!-- Character encoding -->
  <meta charset="UTF-8">

  <!-- Page title -->
  <title>Simple Image Slider</title>

  <style>
    /* Page styling */
    body {
      font-family: Arial, sans-serif;
      background: #f4f4f4;
      text-align: center;
      padding: 40px;
    }

    /* Slider container */
    .slider {
      background: white;
      padding: 20px;
      max-width: 400px;
      margin: auto;
      border-radius: 8px;
    }

    /* Image styling */
    img {
      width: 100%;
      border-radius: 5px;
    }

    /* Button styling */
    button {
      margin: 10px;
      padding: 10px 15px;
      cursor: pointer;
    }
  </style>
</head>

<body>

  <!-- Main slider box -->
  <div class="slider">

    <!-- Title -->
    <h2>Image Slider</h2>

    <!-- Image element (source will change with JavaScript) -->
    <img id="sliderImage" src="" alt="Slider Image">

    <!-- Navigation buttons -->
    <div>
      <button onclick="prevImage()">Previous</button>
      <button onclick="nextImage()">Next</button>
    </div>

  </div>

  <script>
    // Array holding image URLs
    const images = [
      "https://picsum.photos/400/250?random=1",
      "https://picsum.photos/400/250?random=2",
      "https://picsum.photos/400/250?random=3"
    ];

    // Keeps track of which image is currently shown
    let currentIndex = 0;

    // Get the image element from HTML
    const sliderImage = document.getElementById("sliderImage");

    // Show the first image when page loads
    sliderImage.src = images[currentIndex];

    // Function to show next image
    function nextImage() {
      // Move to next index
      currentIndex++;

      // If index goes past last image, go back to first
      if (currentIndex >= images.length) {
        currentIndex = 0;
      }

      // Update image source
      sliderImage.src = images[currentIndex];
    }

    // Function to show previous image
    function prevImage() {
      // Move to previous index
      currentIndex--;

      // If index goes below 0, go to last image
      if (currentIndex < 0) {
        currentIndex = images.length - 1;
      }

      // Update image source
      sliderImage.src = images[currentIndex];
    }
  </script>

</body>
</html>

Typing speed test app in JavaScript

This typing speed test app measures how fast a user types by timing how long it takes to retype a given sentence and then calculating words per minute (WPM); it starts the timer when the user begins typing, counts the number of words entered, and uses basic JavaScript logic with events, time calculation, and DOM manipulation to display the typing speed, making it a practical and beginner-friendly project for understanding real-world JavaScript interactivity.

<!DOCTYPE html>
<html lang="en">
<head>
  <!-- Sets correct character encoding -->
  <meta charset="UTF-8">

  <!-- Title shown in browser tab -->
  <title>Typing Speed Test</title>

  <style>
    /* Style the entire page */
    body {
      font-family: Arial, sans-serif;      /* Simple readable font */
      background: #f4f4f4;                 /* Light background */
      text-align: center;                  /* Center all text */
      padding: 40px;                       /* Space around content */
    }

    /* Main container */
    .box {
      background: white;                   /* White card */
      padding: 20px;                       /* Inner spacing */
      max-width: 500px;                    /* Limit width */
      margin: auto;                        /* Center horizontally */
      border-radius: 8px;                  /* Rounded corners */
    }

    /* Text area for typing */
    textarea {
      width: 100%;                         /* Full width */
      height: 100px;                       /* Fixed height */
      font-size: 16px;                     /* Comfortable text size */
      padding: 10px;                       /* Inner spacing */
    }

    /* Button styling */
    button {
      margin-top: 10px;                    /* Space above button */
      padding: 10px 15px;                  /* Button size */
      cursor: pointer;                     /* Pointer on hover */
    }
  </style>
</head>

<body>

  <!-- Main content box -->
  <div class="box">

    <!-- App heading -->
    <h2>Typing Speed Test</h2>

    <!-- Text the user must type -->
    <p id="text">
      JavaScript is a powerful language for building interactive websites.
    </p>

    <!-- Area where user types -->
    <textarea id="input" placeholder="Start typing here..."></textarea>

    <!-- Button to finish test -->
    <button onclick="checkSpeed()">Check Speed</button>

    <!-- Result output -->
    <p id="result"></p>

  </div>

  <script>
    // Store the text user must type
    const text = document.getElementById("text").textContent;

    // Get the textarea element
    const input = document.getElementById("input");

    // Get the result paragraph
    const result = document.getElementById("result");

    // Variable to store start time
    let startTime = null;

    // Start timer when user begins typing
    input.addEventListener("keydown", function () {
      // If timer has not started yet
      if (startTime === null) {
        // Record current time
        startTime = new Date();
      }
    });

    // Function to calculate typing speed
    function checkSpeed() {

      // Record end time
      const endTime = new Date();

      // Calculate time difference in seconds
      const timeTaken = (endTime - startTime) / 1000;

      // Count total words typed
      const wordsTyped = input.value.trim().split(" ").length;

      // Calculate Words Per Minute (WPM)
      const wpm = Math.round((wordsTyped / timeTaken) * 60);

      // Display result to user
      result.textContent = "Your typing speed is " + wpm + " words per minute.";
    }
  </script>

</body>
</html>

Simple color generator app in JavaScript

This random color generator app allows users to change the background color of the webpage with a single button click by generating a random hexadecimal color code; it uses JavaScript to create the color dynamically, apply it instantly to the pageโ€™s background, and display the generated color code on the screen, helping students understand core concepts such as functions, loops, random number generation, and basic DOM manipulation in a simple and visual way.

<!DOCTYPE html>
<html lang="en">
<head>
  <!-- Sets character encoding so text displays correctly -->
  <meta charset="UTF-8">

  <!-- Title shown in browser tab -->
  <title>Color Generator</title>

  <style>
    /* Style for the whole page */
    body {
      font-family: Arial, sans-serif;     /* Font style */
      text-align: center;                 /* Center text */
      padding: 40px;                      /* Space around content */
      background-color: #ffffff;          /* Initial background color */
    }

    /* Style for the button */
    button {
      padding: 15px 20px;                 /* Button size */
      font-size: 16px;                    /* Text size */
      cursor: pointer;                    /* Hand cursor on hover */
    }

    /* Style for color text */
    #colorCode {
      margin-top: 20px;                   /* Space above text */
      font-size: 20px;                    /* Bigger text */
    }
  </style>
</head>

<body>

  <!-- Page heading -->
  <h1>Random Color Generator</h1>

  <!-- Button that triggers color change -->
  <button onclick="generateColor()">Generate Color</button>

  <!-- Paragraph to show color code -->
  <p id="colorCode">Color: #FFFFFF</p>

  <script>
    // Function that generates a random color
    function generateColor() {

      // Characters used in hexadecimal color codes
      const letters = "0123456789ABCDEF";

      // Starting value for color (must start with #)
      let color = "#";

      // Loop runs 6 times to create a 6-digit color code
      for (let i = 0; i < 6; i++) {

        // Pick a random character from letters
        color += letters[Math.floor(Math.random() * 16)];
      }

      // Change the page background color
      document.body.style.backgroundColor = color;

      // Display the color code on the screen
      document.getElementById("colorCode").textContent = "Color: " + color;
    }
  </script>

</body>
</html>

Simple Quiz App

The logic of this quiz app is simple: all questions are stored in an array as objects, where each object contains the question, options, and the correct answer; a variable called currentQuestion keeps track of which question is currently being shown, and another variable score counts how many answers are correct; when the page loads, the loadQuestion() function displays the first question and its options on the screen; when a user clicks an option button, the checkAnswer() function compares the clicked option with the correct answer of the current question, increases the score if it is correct, and then moves to the next question by increasing currentQuestion; if there are more questions, the next one is loaded after a short delay, and if all questions are finished, the quiz stops and the final score is displayed.

<!DOCTYPE html>
<!-- Defines HTML5 document -->

<html>
<head>
  <title>Multi Question Quiz</title>
</head>

<body>

  <h2>JavaScript Quiz</h2>
  <!-- Quiz heading -->

  <p id="question"></p>
  <!-- Question text will appear here -->

  <button onclick="checkAnswer('a')">A</button>
  <!-- Option A button -->

  <button onclick="checkAnswer('b')">B</button>
  <!-- Option B button -->

  <button onclick="checkAnswer('c')">C</button>
  <!-- Option C button -->

  <p id="result"></p>
  <!-- Shows Correct / Wrong message -->

  <p id="score"></p>
  <!-- Shows score -->

  <script>

    // Array that stores all quiz questions
    let quiz = [
      {
        question: "What is JavaScript?",
        a: "A database",
        b: "A programming language",
        c: "An operating system",
        correct: "b"
      },
      {
        question: "Which symbol is used for comments in JavaScript?",
        a: "//",
        b: "<!-- -->",
        c: "#",
        correct: "a"
      },
      {
        question: "Which keyword is used to declare a variable?",
        a: "var",
        b: "int",
        c: "string",
        correct: "a"
      }
    ];

    let currentQuestion = 0;
    // Keeps track of which question is being shown

    let score = 0;
    // Stores total correct answers

    // Function to load a question
    function loadQuestion() {

      document.getElementById("question").innerHTML =
        quiz[currentQuestion].question + "<br><br>" +
        "a) " + quiz[currentQuestion].a + "<br>" +
        "b) " + quiz[currentQuestion].b + "<br>" +
        "c) " + quiz[currentQuestion].c;

      // Clear previous result
      document.getElementById("result").innerHTML = "";
    }

    // Load first question when page opens
    loadQuestion();

    // Function to check user's answer
    function checkAnswer(answer) {

      if (answer === quiz[currentQuestion].correct) {
        // If answer is correct

        score++;
        // Increase score

        document.getElementById("result").innerHTML = "โœ… Correct!";
      } else {
        // If answer is wrong

        document.getElementById("result").innerHTML = "โŒ Wrong!";
      }

      currentQuestion++;
      // Move to next question

      if (currentQuestion < quiz.length) {
        // If more questions exist

        setTimeout(loadQuestion, 1000);
        // Load next question after 1 second
      } else {
        // Quiz finished

        document.getElementById("question").innerHTML =
          "๐ŸŽ‰ Quiz Finished!";

        document.getElementById("score").innerHTML =
          "Your Score: " + score + " / " + quiz.length;
      }
    }

  </script>

</body>
</html>

Simple JavaScript Site

<!-- Declare HTML5 document -->
<!DOCTYPE html>

<!-- Root HTML element -->
<html lang="en">

<head>
    <!-- Character encoding -->
    <meta charset="UTF-8">

    <!-- Responsive layout for all devices -->
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <!-- Title shown in browser tab -->
    <title>JavaScript Client Demo</title>

    <!-- Link external CSS file -->
    <link rel="stylesheet" href="style.css">
</head>

<body>

    <!-- Main heading -->
    <h1>Client-Side JavaScript Showcase</h1>

    <!-- Input field for user's name -->
    <input type="text" id="nameInput" placeholder="Enter your name">

    <!-- Button to greet user -->
    <button onclick="greetUser()">Greet Me</button>

    <!-- Button to change background color -->
    <button onclick="changeBackground()">Change Background</button>

    <!-- Button to show dialog examples -->
    <button onclick="showDialogs()">Show Dialogs</button>

    <!-- Display message output -->
    <p id="output"></p>

    <!-- Display date and time -->
    <p id="dateTime"></p>

    <!-- Load JavaScript file -->
    <script src="script.js"></script>

</body>

</html>
/* Style the body of the page */
body {
    font-family: Arial, sans-serif; /* Font style */
    text-align: center;             /* Center text */
    background-color: #f2f2f2;      /* Light gray background */
    padding-top: 40px;              /* Space from top */
}

/* Style buttons */
button {
    padding: 10px 15px;             /* Inner spacing */
    margin: 5px;                    /* Space between buttons */
    font-size: 16px;                /* Text size */
    cursor: pointer;                /* Pointer cursor */
}

/* Style input field */
input {
    padding: 8px;                   /* Inner spacing */
    font-size: 16px;                /* Text size */
}

/* Output message styling */
#output {
    margin-top: 20px;               /* Space above */
    font-size: 18px;                /* Text size */
    color: blue;                    /* Text color */
}

/* Date & time styling */
#dateTime {
    margin-top: 10px;               /* Space above */
    font-size: 16px;                /* Text size */
    color: green;                   /* Text color */
}
// Function to greet the user using input field
function greetUser() {

    // Get value from input box
    let name = document.getElementById("nameInput").value;

    // Check if input is empty
    if (name === "") {
        alert("Please enter your name!");
        return;
    }

    // Display greeting message
    document.getElementById("output").innerText =
        "Hello, " + name + "! Welcome to JavaScript.";
}

// Function to change background color randomly
function changeBackground() {

    // Generate random color using RGB values
    let randomColor =
        "rgb(" +
        Math.floor(Math.random() * 256) + "," +
        Math.floor(Math.random() * 256) + "," +
        Math.floor(Math.random() * 256) + ")";

    // Apply background color to body
    document.body.style.backgroundColor = randomColor;
}

// Function to show alert, prompt, and confirm dialogs
function showDialogs() {

    // Show alert message
    alert("This is an alert dialog!");

    // Show prompt dialog and store user input
    let userAge = prompt("Enter your age:");

    // Show confirm dialog
    let isSure = confirm("Do you want to continue?");

    // Display dialog results
    document.getElementById("output").innerText =
        "Age: " + userAge + " | Continue: " + isSure;
}

// Function to update date and time every second
function updateDateTime() {

    // Create new Date object
    let now = new Date();

    // Display current date and time
    document.getElementById("dateTime").innerText =
        "Current Date & Time: " + now.toLocaleString();
}

// Call updateDateTime every 1000 milliseconds (1 second)
setInterval(updateDateTime, 1000);

Read a File In JavaScript

const fs = require('fs');

// Read the file 'example.txt'
fs.readFile('example.txt', 'utf8', (error, data) => {
  if (error) {
    console.log("Error reading file:", error);
  } else {
    // Print file content to console
    console.log("File content:");
    console.log(data);
  }
});

Reading from a File

const fs = require('fs');

// Read the file 'example.txt'
fs.readFile('example.txt', 'utf8', (error, data) => {
  if (error) {
    console.log("Error reading file:", error);
  } else {
    // Print file content to console
    console.log("File content:");
    console.log(data);
  }
});