Author: Saim Khalid

  • Form Validation

    Why? Practice validating user input before submission.

    <form onsubmit="return validate()">
      <input type="text" id="name" placeholder="Name"><br>
      <input type="email" id="email" placeholder="Email"><br>
      <input type="password" id="password" placeholder="Password"><br>
      <button type="submit">Submit</button>
    </form>
    <p id="error"></p>
    
    <script>
    function validate() {
      let name = document.getElementById("name").value;
      let email = document.getElementById("email").value;
      let pwd = document.getElementById("password").value;
    
      if(name === "" || email === "" || pwd === "") {
    
    document.getElementById("error").innerText = "All fields are required!";
    return false;
    } if(pwd.length < 6) {
    document.getElementById("error").innerText = "Password must be at least 6 characters!";
    return false;
    } return true; // submit form } </script>

    Explanation:

    • Prevents form submission if fields are empty.
    • Checks password length.
  • Password Strength Checker

    Why? Learn regex (RegExp) and input validation.

    <input type="password" id="password" placeholder="Enter password">
    <p id="strength"></p>
    
    <script>
    document.getElementById("password").addEventListener("input", function() {
      let pwd = this.value;
      let strength = "Weak";
    
      if(pwd.match(/[a-z]/) && pwd.match(/[A-Z]/) && pwd.match(/[0-9]/) && pwd.length >= 8) {
    
    strength = "Strong";
    } else if(pwd.match(/[a-z]/) && pwd.match(/[0-9]/) && pwd.length >= 6) {
    strength = "Medium";
    } document.getElementById("strength").innerText = "Strength: " + strength; }); </script>

    Explanation:

    • Uses regex to check if password has lowercase, uppercase, number, and length.
    • Displays “Weak”, “Medium”, or “Strong”.
  • Typing Speed Test

    Why? Practice timers, input events, and word comparison.

    <p id="quote">The quick brown fox jumps over the lazy dog</p>
    <textarea id="input" placeholder="Type here..."></textarea>
    <p id="result"></p>
    
    <script>
    let startTime;
    
    document.getElementById("input").addEventListener("focus", () => {
      startTime = new Date();
    });
    
    document.getElementById("input").addEventListener("input", () => {
      let text = document.getElementById("input").value;
      let quote = document.getElementById("quote").innerText;
      
      if(text === quote){
    
    let endTime = new Date();
    let timeTaken = (endTime - startTime)/1000;
    let speed = Math.round((quote.split(" ").length / timeTaken) * 60);
    document.getElementById("result").innerText = ⏱ You typed at ${speed} words per minute!;
    } }); </script>

    Explanation:

    • When user starts typing, timer begins.
    • When typed text matches the quote, timer stops.
    • Calculates words per minute
  • Stopwatch

    Why? Teaches setInterval(), clearInterval(), and time calculation.

    <h2 id="time">00:00:00</h2>
    <button onclick="start()">Start</button>
    <button onclick="stop()">Stop</button>
    <button onclick="reset()">Reset</button>
    
    <script>
    let sec = 0, min = 0, hr = 0;
    let timer;
    
    function start() {
      timer = setInterval(run, 1000);
    }
    
    function run() {
      sec++;
      if(sec == 60) { sec=0; min++; }
      if(min == 60) { min=0; hr++; }
    
      document.getElementById("time").innerText =
    
    ${hr.toString().padStart(2,'0')}:${min.toString().padStart(2,'0')}:${sec.toString().padStart(2,'0')};
    } function stop() { clearInterval(timer); } function reset() { clearInterval(timer); sec=0;min=0;hr=0; document.getElementById("time").innerText="00:00:00"; } </script>

    Explanation:

    • setInterval() increases seconds every second.
    • Handles minute/hour rollover.
    • Stop and reset with clearInterval().
  • Quiz App (Intermediate–Advanced)

    Why? Good for arrays, loops, event handling, and scoring.

    <!DOCTYPE html>
    <html>
    <head>
      <title>Quiz App</title>
    </head>
    <body>
      <h2 id="question"></h2>
      <div id="options"></div>
      <button onclick="nextQuestion()">Next</button>
      <p id="score"></p>
    
      <script>
    
    let questions = &#91;
      { q: "What is 2+2?", a: &#91;"3","4","5"], correct: "4" },
      { q: "Capital of France?", a: &#91;"Berlin","Paris","Rome"], correct: "Paris" }
    ];
    let index = 0, score = 0;
    function loadQuestion() {
      document.getElementById("question").innerText = questions&#91;index].q;
      let opts = "";
      questions&#91;index].a.forEach(option =&gt; {
        opts += &amp;lt;button onclick="checkAnswer('${option}')"&amp;gt;${option}&amp;lt;/button&amp;gt;&amp;lt;br&amp;gt;;
      });
      document.getElementById("options").innerHTML = opts;
    }
    function checkAnswer(ans) {
      if (ans === questions&#91;index].correct) score++;
      document.getElementById("score").innerText = Score: ${score};
    }
    function nextQuestion() {
      index++;
      if (index &lt; questions.length) loadQuestion();
      else document.getElementById("question").innerText = "Quiz Over!";
    }
    loadQuestion();
    </script> </body> </html>

    Explanation:

    • Questions stored in an array.
    • Loads one question at a time with options.
    • Checks correct answer and updates score.
    • Ends quiz when finished.
  • Weather App using API

    Why? Learn fetch() API and working with JSON.

    <!DOCTYPE html>
    <html>
    <head>
      <title>Weather App</title>
    </head>
    <body>
      <h2>🌦 Weather App</h2>
      <input type="text" id="city" placeholder="Enter city">
      <button onclick="getWeather()">Search</button>
      <p id="result"></p>
    
      <script>
    
    async function getWeather() {
      let city = document.getElementById("city").value;
      let apiKey = "your_api_key"; // get free key from openweathermap.org
      let url = https://api.openweathermap.org/data/2.5/weather?q=${city}&amp;amp;appid=${apiKey}&amp;amp;units=metric;
      let response = await fetch(url);
      let data = await response.json();
      if (data.cod === "404") {
        document.getElementById("result").innerText = "City not found!";
      } else {
        document.getElementById("result").innerText =
          `🌍 ${data.name}, ${data.sys.country}  
          🌡 Temp: ${data.main.temp}°C  
          ☁ Weather: ${data.weather&#91;0].description}`;
      }
    }
    </script> </body> </html>

    Explanation:

    • User enters a city name.
    • fetch() calls OpenWeatherMap API.
    • JSON data is parsed and displayed.
  • Image Slider / Carousel

    Why? Learn arrays, DOM manipulation, and auto-sliding with setInterval().

    <!DOCTYPE html>
    <html>
    <head>
      <title>Image Slider</title>
      <style>
    
    img { width: 400px; height: 250px; display: block; margin: auto; }
    button { margin: 10px; padding: 10px; }
    </style> </head> <body> <h2 style="text-align:center">Image Slider</h2> <img id="slider" src="https://picsum.photos/id/1011/400/250"> <div style="text-align:center">
    &lt;button onclick="prev()"&gt;Prev&lt;/button&gt;
    &lt;button onclick="next()"&gt;Next&lt;/button&gt;
    </div> <script>
    let images = &#91;
      "https://picsum.photos/id/1011/400/250",
      "https://picsum.photos/id/1015/400/250",
      "https://picsum.photos/id/1016/400/250",
      "https://picsum.photos/id/1025/400/250"
    ];
    let index = 0;
    function showImage() {
      document.getElementById("slider").src = images&#91;index];
    }
    function next() {
      index = (index + 1) % images.length;
      showImage();
    }
    function prev() {
      index = (index - 1 + images.length) % images.length;
      showImage();
    }
    setInterval(next, 3000); // auto change every 3 seconds
    </script> </body> </html>

    Explanation:

    • Images stored in an array.
    • next() & prev() update index and show image.
    • setInterval(next, 3000) auto-changes image every 3 seconds.
  • Calculator

    Why? Practice event handling, math operations, and DOM updates.

    <!DOCTYPE html>
    <html>
    <head>
      <title>Calculator</title>
      <style>
    
    input { width: 200px; padding: 10px; margin: 5px; }
    button { padding: 10px; margin: 2px; }
    </style> </head> <body> <h2>Simple Calculator</h2> <input type="text" id="display" disabled> <br> <button onclick="press('1')">1</button> <button onclick="press('2')">2</button> <button onclick="press('3')">3</button> <button onclick="press('+')">+</button> <br> <button onclick="press('4')">4</button> <button onclick="press('5')">5</button> <button onclick="press('6')">6</button> <button onclick="press('-')">-</button> <br> <button onclick="press('7')">7</button> <button onclick="press('8')">8</button> <button onclick="press('9')">9</button> <button onclick="press('*')">*</button> <br> <button onclick="press('0')">0</button> <button onclick="press('/')">/</button> <button onclick="calculate()">=</button> <button onclick="clearDisplay()">C</button> <script>
    function press(value) {
      document.getElementById("display").value += value;
    }
    function calculate() {
      let exp = document.getElementById("display").value;
      document.getElementById("display").value = eval(exp);
    }
    function clearDisplay() {
      document.getElementById("display").value = "";
    }
    </script> </body> </html>

    Explanation:

    • Buttons call press() to append numbers/operators.
    • calculate() uses eval() to evaluate expression.
    • clearDisplay() clears input.
  • Digital Clock

    Why? Learn Date() object and updating UI with setInterval().

    <!DOCTYPE html>
    <html>
    <head>
      <title>Digital Clock</title>
    </head>
    <body>
      <h2 id="clock"></h2>
    
      <script>
    
    function showTime() {
      let time = new Date();
      let hours = time.getHours();
      let minutes = time.getMinutes();
      let seconds = time.getSeconds();
      // Format with leading zeros
      hours = (hours &lt; 10 ? "0" : "") + hours;
      minutes = (minutes &lt; 10 ? "0" : "") + minutes;
      seconds = (seconds &lt; 10 ? "0" : "") + seconds;
      document.getElementById("clock").innerText = ${hours}:${minutes}:${seconds};
    }
    setInterval(showTime, 1000); // update every second
    showTime(); // call immediately
    </script> </body> </html>

    Explanation:

    • new Date() → gets current time.
    • setInterval() updates the time every second.
    • Updates <h2> text with formatted time.
  • keyword in JavaScript?

    • Refers to the current execution context.
    • In global → this is window (in browsers).
    • Inside objects → refers to that object.

    Example:

    let person = {
      name: "Ali",
      greet: function() {
    
    console.log("Hello " + this.name);
    } }; person.greet(); //