JavaScript is a powerful programming language that allows developers to build dynamic and interactive web applications. Whether you're just starting out or have years of experience, working on real projects is a great way to improve your JavaScript skills.
This guide presents a collection of practical JavaScript examples that cover a wide range of common tasks and features for web applications.
Each example includes code snippets along with explanations of how they work. By exploring these, you'll gain hands-on experience with key JavaScript concepts and learn how to create more interactive and user-friendly web pages.
Examples
Finding Operating System Details
const os = navigator.platform;
alert("Your Operating System: " + os);
-
navigator.platform: This property returns a string representing the platform (operating system) of the browser. - The alert function is used to display a pop-up box that shows the detected operating system. This is useful for understanding the environment in which your web application is running.
Detecting User's Browser
const browser = navigator.userAgent;
alert("Your Browser: " + browser);
-
navigator.userAgent: This property returns the user-agent string of the browser. It contains information about the browser version, operating system, and other details. - This information can be used for browser-specific functionality or for analytics purposes to understand what browsers your users are using.
Creating a Digital Clock
<div id="clock"></div>
<script>
setInterval(() => {
const now = new Date();
document.getElementById('clock').innerText = now.toLocaleTimeString();
}, 1000);
</script>
-
<div id="clock"></div>: This is an HTML element where the current time will be displayed. -
setInterval(callback, 1000): This JavaScript function repeatedly calls the callback function every 1000 milliseconds (1 second). -
new Date(): Creates a new Date object representing the current date and time. -
now.toLocaleTimeString(): Formats the current time as a human-readable string. -
document.getElementById('clock').innerText = now.toLocaleTimeString(): Updates the content of the div with the current time.
Form Validation
<html>
<head>
<title>Form Validation</title>
</head>
<body>
<form id="myForm">
<input type="text" id="name" placeholder="Enter your name">
<button type="submit">Submit</button>
</form>
<script>
document.getElementById('myForm').addEventListener('submit',
function(event) {
const name = document.getElementById('name').value;
if (!name) {
alert("Name is required");
event.preventDefault();
}
});
</script>
</body>
</html>
-
<form id="myForm">: A form element where users can input their name. -
document.getElementById('myForm').addEventListener('submit', function(event) { ... }): Adds an event listener to the form's submit event. -
document.getElementById('name').value: Gets the value entered in the input field. -
if (!name) { ... }: Checks if the input field is empty. -
alert("Name is required"): Displays an alert if the input field is empty. -
event.preventDefault(): Prevents the form from submitting if the validation fails, ensuring the user corrects their input before proceeding.
Displaying Mouse Coordinates
<div id="coords">Move your mouse over this area.</div>
<script>
document.addEventListener('mousemove', function(event) {
const coords = `X: ${event.clientX}, Y: ${event.clientY}`;
document.getElementById('coords').innerText = coords;
});
</script>
-
<div id="coords">Move your mouse over this area.</div>: A div element to display the mouse coordinates. -
document.addEventListener('mousemove', function(event) { ... }): Adds an event listener to the document's mousemove event. -
const coords = \X: ${event.clientX}, Y: ${event.clientY}: Gets the mouse coordinates relative to the viewport. -
document.getElementById('coords').innerText = coords: Updates the div with the current mouse coordinates.
Generating Random Numbers
<button id="generate">Generate Random Number</button>
<p id="randomNumber"></p>
<script>
document.getElementById('generate').addEventListener('click',
function() {
const randomNumber = Math.floor(Math.random() * 100) + 1;
document.getElementById('randomNumber').innerText = "Random Number: " + randomNumber;
});
</script>
-
<button id="generate">Generate Random Number</button>: A button to generate a random number. -
<p id="randomNumber"></p>: A paragraph to display the generated random number. -
document.getElementById('generate').addEventListener('click', function() { ... }): Adds a click event listener to the button. -
const randomNumber = Math.floor(Math.random() * 100) + 1;: Generates a random number between 1 and 100. -
document.getElementById('randomNumber').innerText = "Random Number: " + randomNumber;: Displays the generated random number in the paragraph.
Changing Background Color Randomly
<button id="randomColor">Change Background Color</button>
<script>
document.getElementById('randomColor').addEventListener('click', function() {
const colors = ['red', 'green', 'blue', 'yellow', 'purple'];
const randomColor = colors[Math.floor(Math.random() * colors.length)];
document.body.style.backgroundColor = randomColor;
});
</script>
-
<button id="randomColor">Change Background Color</button>: A button to change the background color. -
document.getElementById('randomColor').addEventListener('click', function() { ... }): Adds a click event listener to the button. -
const colors = ['red', 'green', 'blue', 'yellow', 'purple'];: An array of color options. -
const randomColor = colors[Math.floor(Math.random() * colors.length)];: Selects a random color from the array. -
document.body.style.backgroundColor = randomColor;: Sets the body's background color to the randomly selected color.
Building a To-Do List
<input type="text" id="taskInput" placeholder="Enter a task">
<button id="addButton">Add Task</button>
<ul id="taskList"></ul>
<script>
document.getElementById('addButton').addEventListener('click', function() {
const task = document.getElementById('taskInput').value;
const li = document.createElement('li');
li.innerText = task;
document.getElementById('taskList').appendChild(li);
});
</script>
-
<input type="text" id="taskInput" placeholder="Enter a task">: An input field for entering tasks. -
<button id="addButton">Add Task</button>: A button to add the task to the list. -
<ul id="taskList"></ul>: An unordered list to display the tasks. -
document.getElementById('addButton').addEventListener('click', function() { ... }): Adds an event listener to the button's click event. -
document.getElementById('taskInput').value: Gets the value entered in the input field. -
const li = document.createElement('li'): Creates a new list item element. -
li.innerText = task: Sets the text of the list item to the entered task. -
document.getElementById('taskList').appendChild(li): Adds the new list item to the task list.
Creating a Dropdown Menu
<select id="dropdown">
<option value="Option 1">Option 1</option>
<option value="Option 2">Option 2</option>
<option value="Option 3">Option 3</option>
</select>
<button id="showSelection">Show Selected Option</button>
<script>
document.getElementById('showSelection').addEventListener('click',
function() {
const selectedOption = document.getElementById('dropdown').value;
alert("Selected Option: " + selectedOption);
});
</script>
-
<select id="dropdown">: A dropdown menu with three options. -
<button id="showSelection">Show Selected Option</button>: A button to show the selected option from the dropdown menu. -
document.getElementById('showSelection').addEventListener('click', function() { ... }): Adds a click event listener to the button. -
const selectedOption = document.getElementById('dropdown').value;: Gets the value of the selected option. -
alert("Selected Option: " + selectedOption);: Displays an alert with the selected option.
Toggling Visibility of an Element
<div id="toggleDiv">This is a toggleable div.</div>
<button id="toggleButton">Toggle Visibility</button>
<script>
document.getElementById('toggleButton').addEventListener('click',
function() {
const div = document.getElementById('toggleDiv');
if (div.style.display === 'none') {
div.style.display = 'block';
} else {
div.style.display = 'none';
}
});
</script>
-
<div id="toggleDiv">This is a toggleable div.</div>: A div element with some text that we want to show or hide. -
<button id="toggleButton">Toggle Visibility</button>: A button to toggle the visibility of the div. -
document.getElementById('toggleButton').addEventListener('click', function() { ... }): Adds a click event listener to the button. -
const div = document.getElementById('toggleDiv');: Selects the div element. -
if (div.style.display === 'none') { div.style.display = 'block'; } else { div.style.display = 'none'; }: Toggles the display property of the div between 'none' (hidden) and 'block' (visible).
Top comments (1)
Did you know this works too:
Though not using
document.getElementById()is considered bad practice, it works anyway in all modern browsers.