Company Data In JavaScript

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>Company Info App</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      padding: 20px;
    }
    button {
      margin: 5px 0;
    }
  </style>
</head>
<body>

  <h1>Company Information</h1>

  <div id="output"></div>

  <button onclick="showCompany()">Show Company Info</button>
  <button onclick="showActivities()">Show Activities</button>
  <button onclick="addActivity()">Add New Activity</button>

  <script src="company.js"></script>
</body>
</html>
// Company data
const company = {
  companyName: "Healthy Candy",
  activities: [
    "food manufacturing",
    "improving kids' health",
    "manufacturing toys"
  ],
  address: {
    street: "2nd street",
    number: "123",
    zipcode: "33116",
    city: "Miami",
    state: "Florida"
  },
  yearOfEstablishment: 2021
};

// Display company info
function showCompany() {
  const output = document.getElementById("output");

  output.innerHTML = `
    <h2>${company.companyName}</h2>
    <p><strong>Established:</strong> ${company.yearOfEstablishment}</p>
    <p><strong>Address:</strong> 
      ${company.address.number} ${company.address.street}, 
      ${company.address.city}, ${company.address.state}
    </p>
  `;
}

// Display activities
function showActivities() {
  const output = document.getElementById("output");

  let activitiesList = "<ul>";
  company.activities.forEach(activity => {
    activitiesList += `<li>${activity}</li>`;
  });
  activitiesList += "</ul>";

  output.innerHTML = `
    <h3>Company Activities</h3>
    ${activitiesList}
  `;
}

// Add a new activity
function addActivity() {
  const newActivity = prompt("Enter a new activity:");

  if (newActivity) {
    company.activities.push(newActivity);
    alert("Activity added!");
  }
}

Word Counter In JavaScript

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Word Counter</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      padding: 20px;
    }
    textarea {
      width: 100%;
      height: 120px;
      font-size: 16px;
      padding: 10px;
    }
  </style>
</head>
<body>

  <!-- Textarea where the user types text -->
  <textarea id="textInput" placeholder="Type your text here..."></textarea>

  <!-- Display word count -->
  <p>Word count: <strong id="wordCount">0</strong></p>

  <!-- JavaScript -->
  <script>
    // Get references to HTML elements
    const textArea = document.getElementById("textInput");
    const wordCountDisplay = document.getElementById("wordCount");

    /**
     * Counts words using regular expression
     * @param {string} text - Input text from textarea
     * @returns {number} - Total number of words
     */
    function countWords(text) {
      // Match all complete words using regex
      // \b  -> word boundary
      // \w+ -> one or more word characters (letters, digits, underscore)
      // g   -> global flag (find all matches)
      const words = text.match(/\b\w+\b/g);

      // If matches exist, return their count
      // If no matches, return 0 (null safety)
      return words ? words.length : 0;
    }

    // Listen for input events (typing, deleting, pasting)
    textArea.addEventListener("input", () => {
      // Get current text from textarea
      const text = textArea.value;

      // Count words and update the UI
      wordCountDisplay.textContent = countWords(text);
    });
  </script>

</body>
</html>

built-in HTML element

This code uses the built-in HTML <progress> element, which visually represents progress using a value and a max attribute. The progress bar starts at a value of 30 out of 100, and when the button is clicked, JavaScript increases the bar’s value by accessing and modifying the value property of the progress element. A condition ensures the value does not exceed the maximum limit, and the browser automatically updates the progress bar’s appearance whenever the value changes.

<!DOCTYPE html>
<html>
<body>

  <!-- Progress element with current value 30 and maximum value 100 -->
  <progress id="progressBar" value="30" max="100"></progress>

  <!-- Button to increase progress -->
  <button onclick="increase()">Increase</button>

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

</body>
</html>
// Get progress bar element
let bar = document.getElementById("progressBar");

// Function to increase progress
function increase() {

  // Increase progress value by 10
  bar.value = bar.value + 10;

  // Limit progress to maximum value
  if (bar.value > 100) {
    bar.value = 100;
  }
}

Mouse Position Tracker

This code tracks the movement of the mouse using the mousemove event, which runs every time the mouse moves on the page. JavaScript provides the mouse position through the event object, where clientX gives the horizontal position and clientY gives the vertical position. These values are stored in variables and then displayed on the page by updating the text content of a paragraph element using DOM manipulation.

<!DOCTYPE html>
<html>
<body>

  <!-- Paragraph to show mouse position -->
  <p id="position">Move your mouse</p>

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

</body>
</html>
// Detect mouse movement
document.addEventListener("mousemove", function(event) {

  // Get horizontal mouse position
  let x = event.clientX;

  // Get vertical mouse position
  let y = event.clientY;

  // Display mouse coordinates
  document.getElementById("position").innerText =
    "X: " + x + " , Y: " + y;

});

Even or Odd Checker in JavaScript

This Even or Odd Checker code works by first taking the number entered by the user from the input field and storing it in a variable when the button is clicked. The program then uses the modulo operator (%) to divide the number by 2 and check the remainder; if the remainder is 0, the number is even, otherwise it is odd. Based on this condition, JavaScript updates the text of the result paragraph using document.getElementById().innerText to display whether the entered number is even or odd.

<!DOCTYPE html>
<html>
<body>

  <input type="number" id="number">
  <button onclick="check()">Check</button>

  <p id="result"></p>

  <script src="script.js"></script>

</body>
</html>
function check() {
  let num = document.getElementById("number").value;

  if (num % 2 === 0) {
    document.getElementById("result").innerText = "Even Number";
  } else {
    document.getElementById("result").innerText = "Odd Number";
  }
}

Simple login validation code in JavaScript

This simple login validation code works by first taking the values entered by the user in the username and password input fields using document.getElementById().value and storing them in variables. When the Login button is clicked, the login() function runs and compares the entered values with predefined correct credentials (for example, username "admin" and password "1234") using an if condition. If both the username and password match exactly, a success message is displayed on the page by updating the text of a paragraph element; otherwise, an error message is shown. In short, the logic checks user input against fixed values and then uses conditional statements and DOM manipulation to display the appropriate result.

<!DOCTYPE html>
<html>
<body>

  <input type="text" id="username" placeholder="Username">
  <input type="password" id="password" placeholder="Password">

  <button onclick="login()">Login</button>

  <p id="result"></p>

  <script src="script.js"></script>

</body>
</html>
function login() {
  let user = document.getElementById("username").value;
  let pass = document.getElementById("password").value;

  if (user === "admin" && pass === "1234") {
    document.getElementById("result").innerText = "Login Successful";
  } else {
    document.getElementById("result").innerText = "Wrong Credentials";
  }
}



Digital Clock

<!DOCTYPE html>
<html>
<head>
  <title>Digital Clock</title>
</head>
<body>

  <!-- Heading to display time -->
  <h1 id="clock"></h1>

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

</body>
</html>
// Function to display current time
function showTime() {

  // Create a Date object
  let time = new Date();

  // Get hours from time
  let hours = time.getHours();

  // Get minutes from time
  let minutes = time.getMinutes();

  // Get seconds from time
  let seconds = time.getSeconds();

  // Add 0 before single digit numbers
  if (hours < 10) hours = "0" + hours;
  if (minutes < 10) minutes = "0" + minutes;
  if (seconds < 10) seconds = "0" + seconds;

  // Display time in HH:MM:SS format
  document.getElementById("clock").innerText =
    hours + ":" + minutes + ":" + seconds;
}

// Call function every 1 second
setInterval(showTime, 1000);

Counter App In JavaScript

This counter app works by first displaying a number inside an <h1> element, which starts at 0, and storing that value in a JavaScript variable called count. When you click any button, it calls a specific JavaScript function using the onclick attribute. The Increase button runs the increase() function, which adds 1 to the count variable and then updates the displayed number by selecting the <h1> element using document.getElementById("count") and changing its innerText. The Decrease button works the same way but subtracts 1 from count using the decrease() function. The Reset button calls the reset() function, which sets count back to 0 and updates the display again. In short, the logic is: store a value in a variable, change that value when a button is clicked, and immediately reflect the new value on the webpage using DOM manipulation.

<!DOCTYPE html>
<html>
<head>
  <title>Counter App</title>
</head>
<body>

  <!-- Heading to show the counter value -->
  <h1 id="count">0</h1>

  <!-- Button to increase count -->
  <button onclick="increase()">Increase</button>

  <!-- Button to decrease count -->
  <button onclick="decrease()">Decrease</button>

  <!-- Button to reset count -->
  <button onclick="reset()">Reset</button>

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

</body>
</html>
// Create a variable to store count value
let count = 0;

// Function to increase the count
function increase() {
  count = count + 1;               // Add 1 to count
  document.getElementById("count").innerText = count; // Update text
}

// Function to decrease the count
function decrease() {
  count = count - 1;               // Subtract 1 from count
  document.getElementById("count").innerText = count; // Update text
}

// Function to reset the count
function reset() {
  count = 0;                       // Set count back to 0
  document.getElementById("count").innerText = count; // Update text
}

Add To Cart Example In JavaScript

<!DOCTYPE html>
<html>
<head>
  <title>Simple JS Cart</title>
</head>
<body>

<h2>Products</h2>
<div>
  <button onclick="addToCart('Apple', 1.00)">Add Apple ($1)</button>
  <button onclick="addToCart('Banana', 0.50)">Add Banana ($0.50)</button>
  <button onclick="addToCart('Orange', 0.80)">Add Orange ($0.80)</button>
</div>

<h2>Your Cart</h2>
<ul id="cart-list"></ul>
<p><strong>Total: $<span id="total">0.00</span></strong></p>

<script src="cart.js"></script>
</body>
</html>
// Create an empty array to store cart items
let cart = [];

// Function that runs when a product is added to the cart
function addToCart(name, price) {

  // Search the cart for an item with the same name
  // `i` represents each item while looping through the array
  const item = cart.find(i => i.name === name);

  // If the item already exists in the cart
  if (item) {
    // Increase its quantity by 1
    item.qty++;
  } else {
    // Otherwise, add a brand new item object to the cart
    cart.push({ name, price, qty: 1 });
  }

  // Update the cart display on the webpage
  updateCart();
}

// Function to refresh and show the current cart items
function updateCart() {

  // Get the HTML <ul> element where items will be displayed
  const list = document.getElementById("cart-list");

  // Get the HTML <span> where the total price will appear
  const totalEl = document.getElementById("total");

  // Clear the previous cart display
  list.innerHTML = "";

  // Start total price at 0
  let total = 0;

  // Loop through all items in the cart
  cart.forEach(item => {

    // Add this item's total cost (price × quantity) to the total
    total += item.price * item.qty;

    // Create a new list item <li> for this cart entry
    const li = document.createElement("li");

    // Set the text, e.g. "Apple x 2 - $2.00"
    li.textContent = `${item.name} x ${item.qty} - $${(item.price * item.qty).toFixed(2)}`;

    // Add this <li> to the <ul> list
    list.appendChild(li);
  });

  // Update the total price on screen
  totalEl.textContent = total.toFixed(2);
}

Student registers using a form in JavaScript

This code creates a simple student registration system using an HTML form and JavaScript. When the user submits the form, JavaScript prevents the page from reloading, collects the entered name, email, and course, and stores each student as an object inside an array. The array is saved in localStorage, so the list of registered students remains even after the page is refreshed. Each time a student is added, the updated list is displayed on the page by looping through the array and printing each student’s information. This allows multiple students to be registered, stored permanently in the browser, and shown as a list.

<!DOCTYPE html>
<html>
<head>
    <title>Student Registration</title>
</head>
<body>

<h2>Student Registration Form</h2>

<form id="studentForm">
    <label>Name:</label><br>
    <input type="text" id="name" required><br><br>

    <label>Email:</label><br>
    <input type="email" id="email" required><br><br>

    <label>Course:</label><br>
    <input type="text" id="course" required><br><br>

    <button type="submit">Register</button>
</form>

<h3>Registered Students:</h3>
<ul id="studentList"></ul>

<script src="script.js"></script>
</body>
</html>
let students = [];  // Array to store all registered students

document.getElementById("studentForm").addEventListener("submit", function(event) {
    event.preventDefault();

    // Create student object
    const student = {
        name: document.getElementById("name").value,
        email: document.getElementById("email").value,
        course: document.getElementById("course").value
    };

    // Add student to array
    students.push(student);

    // Display student list
    displayStudents();

    // Clear form
    this.reset();
});

function displayStudents() {
    const list = document.getElementById("studentList");
    list.innerHTML = ""; // Clear list before updating

    students.forEach((student, index) => {
        list.innerHTML += `<li>${index + 1}. ${student.name} - ${student.email} - ${student.course}</li>`;
    });
}