JavaScript


Beginners To Experts


The site is under development.

Javascript Projects

Prerequisite:
1. Get your free API key from https://openweathermap.org/api
2. Replace YOUR_API_KEY_HERE with your real API key in the code

Calculator 1 - Basic

Calculator 2 - More Advanced

1. Replace the API Key

In the code, find this line:

const apiUrl = 'https://cors-anywhere.herokuapp.com/https://api.spoonacular.com/recipes/complexSearch?query={ingredient}&apiKey=YOUR_API_KEY';

Replace YOUR_API_KEY with your real Spoonacular API key.

You can get your key from: https://spoonacular.com/food-api

Example:

const apiUrl = 'https://cors-anywhere.herokuapp.com/https://api.spoonacular.com/recipes/complexSearch?query={ingredient}&apiKey=123456abcdef';

2. Open It in a Browser

  • Locate the recipe-finder.html file on your computer.
  • Double-click the file, and it will open in your default browser.

Try entering an ingredient like:

chicken

Then click the Search button.

3. (Optional) Fix CORS Issue

Option A (Quick Dev Workaround):

Option B (Advanced/Recommended):

  • Use a backend (like Node.js, Flask, etc.) to call the API from the server side, which avoids CORS altogether.

To Run the Movie Search App, Follow These Simple Steps:

Step-by-Step Guide

1. Get an OMDb API Key

This app uses the OMDb API, so you need an API key.

2. Create an HTML File

  • Open a text editor (like VS Code, Notepad, or any code editor)
  • Copy the full HTML code I gave you above
  • Paste it into a new file
  • Save the file as: movie-app.html

3. Insert Your API Key

Find this line in the code:

const apiKey = 'YOUR_API_KEY';

Replace 'YOUR_API_KEY' with the key you got from OMDb, like:

const apiKey = 'abc12345';

4. Open in Browser

  • Locate the saved movie-app.html file
  • Double-click it → It will open in your default browser
  • Now type a movie name (e.g., Matrix) in the input field
  • → The search results will appear instantly

Notes

The app works without a server. It’s pure HTML + JS.

If nothing appears, check:

  • Console errors (press F12 → Console)
  • That your API key is valid
  • That you’re connected to the internet

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Blog Website</title>

  <style>
    * {
      box-sizing: border-box;
      font-family: Arial, sans-serif;
    }
    body {
      margin: 0;
      padding: 20px;
      background-color: #f9f9f9;
    }
    .container {
      max-width: 800px;
      margin: auto;
      background: white;
      padding: 20px;
      border-radius: 10px;
      box-shadow: 0 0 10px rgba(0,0,0,0.1);
    }
    h1 {
      text-align: center;
      color: #333;
    }
    input, textarea, button {
      width: 100%;
      padding: 10px;
      margin-top: 10px;
      margin-bottom: 10px;
      border-radius: 5px;
      border: 1px solid #ccc;
    }
    button {
      background-color: #28a745;
      color: white;
      cursor: pointer;
    }
    button:hover {
      background-color: #218838;
    }
    .blog-post {
      padding: 15px;
      margin: 10px 0;
      border: 1px solid #ddd;
      border-radius: 5px;
      background-color: #fff;
    }
    .blog-title {
      font-size: 24px;
      color: #333;
    }
    .blog-content {
      font-size: 16px;
      color: #555;
      margin-top: 10px;
    }
    .button-container {
      display: flex;
      justify-content: flex-end;
      gap: 10px;
    }
    .delete-btn {
      background-color: red;
      color: white;
      border: none;
      padding: 5px 10px;
      border-radius: 3px;
      cursor: pointer;
    }
    .delete-btn:hover {
      background-color: darkred;
    }
    .edit-btn {
      background-color: #ffc107;
      color: white;
      border: none;
      padding: 5px 10px;
      border-radius: 3px;
      cursor: pointer;
    }
    .edit-btn:hover {
      background-color: #e0a800;
    }
    @media (max-width: 600px) {
      .container {
        padding: 10px;
      }
      input, textarea, button {
        padding: 8px;
      }
      .blog-title {
        font-size: 20px;
      }
      .blog-content {
        font-size: 14px;
      }
    }
  </style>
</head>
<body>
  <div class="container">
    <h1>Blog Website</h1>
    <input type="text" id="title" placeholder="Enter Blog Title">
    <textarea id="content" placeholder="Write your blog content..." rows="5"></textarea>
    <button onclick="addPost()">Add Blog Post</button>
    <div id="blogPosts"></div>
  </div>

  <script>
    let posts = [];
    function addPost() {
      const title = document.getElementById('title').value;
      const content = document.getElementById('content').value;
      if (!title || !content) {
        alert('Please fill in both title and content');
        return;
      }
      const newPost = {
        title: title,
        content: content,
        id: posts.length + 1
      };
      posts.push(newPost);
      displayPosts();
      document.getElementById('title').value = '';
      document.getElementById('content').value = '';
    }

    function displayPosts() {
      const blogPostsContainer = document.getElementById('blogPosts');
      blogPostsContainer.innerHTML = '';
      posts.forEach(post => {
        const postDiv = document.createElement('div');
        postDiv.classList.add('blog-post');
        postDiv.innerHTML = `
          <div class="blog-title">${post.title}</div>
          <div class="blog-content">${post.content}</div>
          <div class="button-container">
            <button class="edit-btn" onclick="editPost(${post.id})">Edit</button>
            <button class="delete-btn" onclick="deletePost(${post.id})">Delete</button>
          </div>
        `;
        blogPostsContainer.appendChild(postDiv);
      });
    }

    function deletePost(postId) {
      posts = posts.filter(post => post.id !== postId);
      displayPosts();
    }

    function editPost(postId) {
      const post = posts.find(post => post.id === postId);
      document.getElementById('title').value = post.title;
      document.getElementById('content').value = post.content;
      deletePost(postId);
    }
  </script>
</body>
</html>
  

Vertical Preview

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8"> <!-- Set character encoding -->
  <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Ensure responsive design -->
  <title>Enhanced Markdown Previewer</title> <!-- Title of the page -->

  <style>
    body {
      font-family: Arial, sans-serif;
      margin: 0;
      padding: 0;
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100vh;
      background-color: #f4f4f4;
    }
    .container {
      display: flex;
      width: 80%;
      max-width: 1000px;
      height: 80%;
      background-color: #fff;
      box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.1);
      border-radius: 8px;
    }
    .editor {
      width: 50%;
      padding: 20px;
      border-right: 1px solid #ddd;
    }
    .preview {
      width: 50%;
      padding: 20px;
      overflow-y: auto;
      background-color: #f9f9f9;
    }
    textarea {
      width: 100%;
      height: 90%;
      padding: 10px;
      font-size: 16px;
      border: 1px solid #ddd;
      border-radius: 4px;
      resize: none;
    }
    .preview-content {
      font-size: 16px;
      color: #333;
    }
    pre {
      background-color: #f2f2f2;
      padding: 10px;
      border-radius: 4px;
      overflow-x: auto;
    }
    code {
      background-color: #f4f4f4;
      padding: 2px 4px;
      border-radius: 4px;
    }
    a {
      color: #3498db;
      text-decoration: none;
    }
    a:hover {
      text-decoration: underline;
    }
    img {
      max-width: 100%;
      height: auto;
      border-radius: 4px;
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="editor">
      <h2>Editor</h2>
      <textarea id="markdownInput" placeholder="Write your markdown here..." oninput="updatePreview()"></textarea>
    </div>
    <div class="preview">
      <h2>Preview</h2>
      <div id="markdownPreview" class="preview-content"></div>
    </div>
  </div>

  <script>
    function updatePreview() {
      const markdownText = document.getElementById('markdownInput').value;
      const htmlContent = marked(markdownText);
      document.getElementById('markdownPreview').innerHTML = htmlContent;
    }
    document.getElementById('markdownInput').value = `
# Markdown Previewer
Welcome to the **Markdown Previewer**!
## Features
- **Real-time preview**
- **Links**, **images**, **code blocks**

\`\`\`
function helloWorld() {
  console.log('Hello, World!');
}
\`\`\`

[Google](https://www.google.com)

![Example Image](https://via.placeholder.com/150)
`;
    window.onload = updatePreview;
  </script>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/marked/2.1.3/marked.min.js"></script>
</body>
</html>
  

Horizontal Preview

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Markdown Previewer</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      margin: 0;
      padding: 0;
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100vh;
      background-color: #f4f4f4;
    }
    .container {
      display: flex;
      flex-wrap: wrap;
      width: 90%;
      max-width: 1200px;
      height: 80%;
      background-color: #fff;
      box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.1);
      border-radius: 10px;
    }
    .editor {
      width: 50%;
      padding: 20px;
      border-right: 1px solid #ddd;
    }
    .preview {
      width: 50%;
      padding: 20px;
      overflow-y: auto;
      background-color: #f9f9f9;
    }
    textarea {
      width: 100%;
      height: 90%;
      padding: 10px;
      font-size: 16px;
      border: 1px solid #ddd;
      border-radius: 4px;
      resize: none;
    }
    .preview-content {
      font-size: 16px;
      color: #333;
    }
    pre {
      background-color: #f2f2f2;
      padding: 10px;
      border-radius: 4px;
      overflow-x: auto;
    }
    code {
      background-color: #f4f4f4;
      padding: 2px 4px;
      border-radius: 4px;
    }
    a {
      color: #3498db;
      text-decoration: none;
    }
    a:hover {
      text-decoration: underline;
    }
    img {
      max-width: 100%;
      height: auto;
      border-radius: 4px;
    }
    @media (max-width: 768px) {
      .editor, .preview {
        width: 100%;
      }
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="editor">
      <h2>Markdown Editor</h2>
      <textarea id="markdownInput" placeholder="Write your markdown here..." oninput="updatePreview()"></textarea>
    </div>
    <div class="preview">
      <h2>Preview</h2>
      <div id="markdownPreview" class="preview-content"></div>
    </div>
  </div>

  <script>
    function updatePreview() {
      const markdownText = document.getElementById('markdownInput').value;
      const htmlContent = marked(markdownText);
      document.getElementById('markdownPreview').innerHTML = htmlContent;
    }

    document.getElementById('markdownInput').value = `
# Welcome to the Markdown Previewer!
This is a simple Markdown Previewer.

## Features
- **Real-time preview**
- **Support for code blocks**
- **Links** and **Images**

\`\`\`
function sayHello() {
  console.log('Hello, Markdown!');
}
\`\`\`

[Google](https://www.google.com)

![Sample Image](https://via.placeholder.com/150)
`;
    window.onload = updatePreview;
  </script>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/marked/2.1.3/marked.min.js"></script>
</body>
</html>
  

Simple Quiz App

Advanced Quiz App

Quiz Features

Reset Button:

  • A reset button is added below the "Start Quiz" button. It’s initially hidden and shown only after the quiz starts.
  • When clicked, the reset button resets the score, timer, and question index, effectively restarting the quiz.

Beep Sound:

  • The playBeep() function plays a beep sound when the timer runs out.
  • The beep sound file is fetched from a URL (https://www.soundjay.com/button/beep-07.wav), but you can replace this URL with any desired sound file.

Timer:

  • The timer starts at 60 seconds and updates the remaining time on the screen every second.
  • When the timer reaches 0, the beep sound plays, and the result is displayed.

Next Game

Third Game

Fourth game French-English Words

First App

Second App - question - Answer

Single-Page Form

Multi-Page Survey Form

Important Notes

API Key: You need to replace 'YOUR_API_KEY_HERE' with an actual API key from NewsAPI. Without a valid key, the fetch request won't work.

CORS Issue: If you're testing it locally, your browser might block the API request due to CORS (Cross-Origin Resource Sharing). If that’s the case, try using a local server like VS Code Live Server or a similar tool, or host it on a server to avoid CORS issues.

Important Instructions

Get your API Key: Go to OpenWeatherMap and create a free account. After signing in, go to the API section and generate an API key. Replace 'YOUR_API_KEY' in the code with this key.

Run Locally: Save the code in an .html file and open it in your browser. If you're running it on your local machine, it should work. If you encounter CORS issues, try running it from a local server (you can use a tool like Live Server if you're using VS Code).

Check Developer Console: If the data isn't displayed correctly, check the browser console for error messages (right-click > Inspect > Console).

Shopping Cart Checkout Form

Persistent View Count Across Reloads

Option 1: localStorage (Client-Side Only)

Views are saved in the user’s browser.

  • Simple, no server needed
  • Not shared between users
Solution A: Using localStorage
Quick and works per device/browser.

Add this inside your <script> tag:

// Load and initialize view counts from localStorage
document.querySelectorAll('.item').forEach(item => {
  const id = item.getAttribute('data-id'); // Get unique ID
  const storedCount = localStorage.getItem('view-' + id);
  if (storedCount) {
    item.querySelector('.view-count').textContent = storedCount;
  }
});

Modify the click event:

Before:

let currentCount = parseInt(viewCountEl.textContent);
currentCount++;
viewCountEl.textContent = currentCount;

After:

let currentCount = parseInt(viewCountEl.textContent);
currentCount++;
viewCountEl.textContent = currentCount;
localStorage.setItem('view-' + id, currentCount);

Option 2: Server-Side View Tracking (Recommended)

For hosted sites with multiple users.

  • Shared across devices
  • Real counts
  • Requires backend/database
Solution B: Using Firebase
Real-time shared view counter across users.

Load Firebase SDK in HTML:

<script src="https://www.gstatic.com/firebasejs/9.6.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/9.6.1/firebase-database.js"></script>

Initialize Firebase:

const firebaseConfig = {
  apiKey: "YOUR_KEY",
  authDomain: "YOUR_DOMAIN",
  databaseURL: "https://YOUR_DB.firebaseio.com",
  projectId: "YOUR_PROJECT_ID"
};

firebase.initializeApp(firebaseConfig);
const db = firebase.database();

Fetch & Update View Count:

const id = item.getAttribute('data-id');
const viewRef = db.ref('views/' + id);

viewRef.once('value').then(snapshot => {
  let views = snapshot.val() || 0;
  views++;
  viewRef.set(views); // Save new count
  viewCountEl.textContent = views; // Show in UI
});

Summary

Method Works Offline? Shared Across Users? Requires Server?
localStorage ✅ Yes ❌ No ❌ No
Firebase ❌ No ✅ Yes ✅ Yes
Node.js + DB ❌ No ✅ Yes ✅ Yes


Have the viewr on a website updated , show the real numbers of clicks

Only do this for demos. For production, set proper authentication and rules.

Result

Each item shows its view count.

When clicked, it updates both:

  • Visually in the UI.
  • Persistently in Firebase (shared with all users).

View count continues to increase, even across devices or reloads.

Note: Use Firebase for a real demo setup. Ensure to adjust read/write rules in Firebase console.

View Counter Example

Viewer Count Demo

Total number of views

Updates live when clicked

Stores data online (so the number persists and is shared across devices)

Simple and Free Online Setup Using Firebase Realtime Database

Firebase is a cloud-based backend by Google. It lets you store data like view counts without writing a custom backend server.

Step-by-Step Guide (Fully Explained)

1. Create a Firebase Project

  • Go to Firebase Console
  • Click Add project, name it (e.g., "ViewTracker")
  • Skip Google Analytics
  • Click Create

2. Add Firebase to Your Website

Go to your project → click Web → Register app → Get your config snippet.

Paste this inside your or before :






    

3. HTML Page with Items to Track Views

Image 1 👁️ 0 views
Visit Page 👁️ 0 views

4. JavaScript to Handle Viewing and Count Update


    

5. Allow Public Read/Write Access (for test/demo only)

{
  "rules": {
    ".read": true,
    ".write": true
  }
}
    

How to Run the App - Stock Price Tracker

API Key:

To use this app, you'll need an API key from a stock data provider like Finnhub. Follow these steps to get the API key:

  • Create a free account on a stock data provider's website (such as Finnhub).
  • Once registered, navigate to the API section and generate a free API key.
  • Copy the generated API key to use in the app.

Save and Run:

  • Save the HTML code in a file called stock-price-tracker.html.
  • Open the file in any modern web browser (e.g., Chrome, Firefox, Edge).
  • Enter a stock symbol (e.g., AAPL) into the input field and click the "Get Price" button to see the stock details.


Another Music Player

Youtube Player

Steps to Run the Job Search App Locally on Your Computer

1. Prepare Your Files:

  • Copy the HTML Code: Copy the HTML code provided (e.g., job-search-app) into a text editor.
  • Open a Text Editor: You can use any text editor like Notepad, Visual Studio Code, Sublime Text, etc.
  • Paste the HTML Code: Paste the HTML code into your editor.
  • Save the File: Save the file with the .html extension. For example, name it job-search-app.html.

2. Open the File in a Web Browser:

  • Locate the File: After saving the file, navigate to the directory where you saved it.
  • Open the File: Double-click on the saved .html file, and it will open in your default web browser (such as Google Chrome, Mozilla Firefox, Edge, etc.).

3. Interact with the App:

  • Use the Search Bar: Enter a job title or company name into the search field and click the Search button.
  • Use Filters: You can filter the results by Full-time, Part-time, or Remote job types.
  • View Results: The filtered job listings will appear below the search bar as per your input.

Alternative Method: Running the App Using a Local Web Server

For a more complex project setup, you might want to simulate a production environment or interact with APIs using a local web server. Here’s how you can do that:

1. Install a Local Server:

  • Use XAMPP (for Apache and MySQL): Download and install XAMPP, which comes with Apache (for serving your app) and MySQL (if you plan to use a database).
  • Use Live Server in Visual Studio Code: Download and install Visual Studio Code. Open Visual Studio Code, then go to the Extensions tab and search for Live Server. Install the Live Server extension.

2. Open Your App in Visual Studio Code Using Live Server:

  • Open Your HTML File: Open the job-search-app.html file in Visual Studio Code.
  • Right-click to Open with Live Server: Right-click on the HTML file and select Open with Live Server. This will open your app in the default web browser.
  • Live Interaction: You can now make live changes to the app (e.g., modify the HTML, CSS, or JavaScript) and see them reflected in real-time in your browser.

Running the App on the Web:

If you want to share your app with others or make it publicly accessible online, you can host it on a web hosting platform.

1. Host on GitHub Pages:

  • Create a GitHub Account: Go to GitHub and sign up for an account.
  • Create a New Repository: After logging in to GitHub, click on the New Repository button. Name it something like job-search-app.
  • Upload Your Files: Upload the HTML file (and any related files, like CSS or JavaScript) to the repository.
  • Enable GitHub Pages: Go to the repository’s settings. Scroll down to the GitHub Pages section. Select the main branch as the source (or the folder containing your files). Save the settings.
  • Access Your App: Once the changes are saved, your app will be live. The URL will be https://your-username.github.io/repository-name. For example: https://johnDoe.github.io/job-search-app.

2. Host on Other Platforms (Netlify, Vercel, etc.):

  • Netlify: Go to Netlify and sign up. Upload your project files to Netlify. After uploading, Netlify will provide you with a URL where your app is hosted.
  • Vercel: Visit Vercel, create an account, and link it with your GitHub repository. Deploy the project directly from the repository to get a live URL.