// Import the built-in 'fs' (file system) module
const fs = require('fs');
// Text we want to write into the file
const content = "Hello! This text is written to a file using Node.js.";
// Write to a file called 'example.txt'
fs.writeFile('example.txt', content, (error) => {
if (error) {
// If an error happens, print it
console.log("Error writing file:", error);
} else {
// If successful
console.log("File written successfully!");
}
});
Author: admin
Person Class Example
This project demonstrates how a JavaScript class works using a simple Person example. The Person class is a blueprint used to create person objects, each containing a first name and a last name. The constructor initializes these values when a new object is created. A method called getFullName() combines and returns the first and last names. In the HTML, a button is provided that triggers the showPerson() function when clicked. This function creates a new Person object, calls its method to get the full name, and then displays the result dynamically on the webpage. This shows how JavaScript classes, objects, methods, and DOM manipulation work together in a basic project.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Person Class Example</title>
</head>
<body>
<!-- Heading shown on the webpage -->
<h1>JavaScript Person Class Example</h1>
<!-- Button to trigger JavaScript function -->
<button onclick="showPerson()">Show Person Details</button>
<!-- Paragraph where output will be displayed -->
<p id="output"></p>
<script>
// Define a class named Person
class Person {
// Constructor method runs when a new object is created
constructor(firstname, lastname) {
// Assign the firstname parameter to the object's firstname property
this.firstname = firstname;
// Assign the lastname parameter to the object's lastname property
this.lastname = lastname;
}
// Method to return the full name of the person
getFullName() {
// Combine firstname and lastname and return them
return this.firstname + " " + this.lastname;
}
}
// Function that runs when the button is clicked
function showPerson() {
// Create a new Person object with first and last name
const person1 = new Person("John", "Doe");
// Get the paragraph element by its ID
const outputElement = document.getElementById("output");
// Display the full name inside the paragraph
outputElement.textContent = "Full Name: " + person1.getFullName();
}
</script>
</body>
</html>
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
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;
}
}
Disable Right Click
This code disables the browser’s right-click menu by listening for the contextmenu event, which occurs when the user right-clicks anywhere on the page. When the event is detected, event.preventDefault() stops the browser from showing its default menu, and an alert message is displayed to inform the user that right-clicking is disabled.
<!DOCTYPE html> <html> <body> <h2>Right Click is Disabled</h2> <script src="script.js"></script> </body> </html>
// Add event listener for right click
document.addEventListener("contextmenu", function(event) {
// Prevent default right-click menu
event.preventDefault();
// Show alert message
alert("Right click is disabled!");
});
Key Press Detector
This code listens for any key pressed on the keyboard using the keydown event listener attached to the document. When a key is pressed, JavaScript automatically provides an event object that contains information about the key, including which key was pressed. The code accesses event.key to get the key value and then updates the text inside the heading element using innerText to display the pressed key on the screen.
<!DOCTYPE html> <html> <body> <!-- Heading to show pressed key --> <h2 id="output">Press any key</h2> <!-- Link JavaScript --> <script src="key.js"></script> </body> </html>
// Add event listener for key press
document.addEventListener("keydown", function(event) {
// Display the key pressed by the user
document.getElementById("output").innerText =
"You pressed: " + event.key;
});
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";
}
}