Alright, let’s dive into some practical JavaScript examples that illustrate core concepts and common use cases. These “tutoriles” (tutorial examples) will help solidify your understanding of how JavaScript works in real-world scenarios.
Example 1: Basic DOM Manipulation and Event Handling
This is a fundamental skill in web development: making your page interactive.
HTML:
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JS Example 1: DOM & Events</title>
<style>
body { font-family: Arial, sans-serif; display: flex; flex-direction: column; align-items: center; justify-content: center; min-height: 100vh; background-color: #f0f0f0; }
#message { margin-top: 20px; padding: 15px; border: 1px solid #ccc; background-color: #e9e9e9; border-radius: 5px; }
button { padding: 10px 20px; font-size: 16px; cursor: pointer; background-color: #007bff; color: white; border: none; border-radius: 5px; }
button:hover { background-color: #0056b3; }
</style>
</head>
<body>
<button id="myButton">Click Me!</button>
<div id="message">No message yet.</div>
<script>
// JavaScript code goes here
</script>
</body>
</html>
JavaScript (<script>
section):
JavaScript
document.addEventListener('DOMContentLoaded', function() {
// 1. Get references to HTML elements
const myButton = document.getElementById('myButton');
const messageDiv = document.getElementById('message');
// 2. Define a function to be executed when the button is clicked
function handleClick() {
messageDiv.textContent = 'Button was clicked!'; // Change text content
messageDiv.style.backgroundColor = '#d4edda'; // Change background style
messageDiv.style.borderColor = '#28a745'; // Change border color
messageDiv.style.color = '#155724'; // Change text color
}
// 3. Attach an event listener to the button
myButton.addEventListener('click', handleClick);
// Optional: Change initial message after a short delay
setTimeout(() => {
messageDiv.textContent = 'Welcome! Click the button above.';
messageDiv.style.backgroundColor = '#ffeeba';
messageDiv.style.borderColor = '#ffc107';
messageDiv.style.color = '#856404';
}, 1000); // 1000 milliseconds = 1 second
});
Explanation:
document.addEventListener('DOMContentLoaded', ...)
: Ensures the JavaScript runs only after the entire HTML document has been loaded and parsed. This prevents errors if you try to select elements that don’t exist yet.document.getElementById()
: A common method to get a reference to an element using its uniqueid
.element.textContent = '...'
: Sets or gets the text content of an element.element.style.propertyName = 'value'
: Directly sets inline CSS styles for an element.element.addEventListener('event', function)
: Attaches a function to be executed when a specific event (like'click'
) occurs on the element.setTimeout(() => {}, delay)
: Executes a function once after a specified delay.
Example 2: Working with Arrays and Loops
Arrays are fundamental data structures, and loops are essential for processing collections of data.
HTML: (Add this to the <body>
of the previous HTML, or create a new file)
HTML
<h2>Grocery List</h2>
<ul id="groceryList">
</ul>
JavaScript (<script>
section):
JavaScript
document.addEventListener('DOMContentLoaded', function() {
const groceries = ['Apples', 'Bread', 'Milk', 'Eggs', 'Cheese'];
const groceryList = document.getElementById('groceryList');
// Loop through the array and add each item to the list
for (let i = 0; i < groceries.length; i++) {
const listItem = document.createElement('li'); // Create a new <li> element
listItem.textContent = groceries[i]; // Set its text content
groceryList.appendChild(listItem); // Add it to the <ul>
}
// Add another item dynamically
const newItem = 'Yogurt';
groceries.push(newItem); // Add to the array
const newListItem = document.createElement('li');
newListItem.textContent = newItem;
groceryList.appendChild(newListItem);
console.log("Updated Groceries:", groceries); // Check array in console
// A more modern way to iterate (forEach)
// You might clear the list first if reusing: groceryList.innerHTML = '';
// groceries.forEach(item => {
// const listItem = document.createElement('li');
// listItem.textContent = `(forEach) ${item}`;
// groceryList.appendChild(listItem);
// });
});
Explanation:
const array = [...]
: Defines an array literal.array.length
: Gets the number of elements in the array.for (let i = 0; i < array.length; i++)
: A classicfor
loop for iterating by index.document.createElement('tagName')
: Creates a new HTML element node.parentElement.appendChild(childElement)
: Appends a child element to a parent.array.push(item)
: Adds an item to the end of an array.array.forEach(callbackFunction)
: A higher-order array method that executes a provided function once for each array element. Often preferred overfor
loops for array iteration.
Example 3: Simple Form Validation
A common scenario where JavaScript ensures data quality before submission.
HTML: (Add this to the <body>
)
HTML
<h2>Simple Form Validation</h2>
<form id="myForm">
<label for="email">Email:</label>
<input type="email" id="email" required><br><br>
<label for="password">Password (min 6 chars):</label>
<input type="password" id="password" required minlength="6"><br><br>
<button type="submit">Submit</button>
<p id="validationMessage" style="color: red;"></p>
</form>
JavaScript (<script>
section):
JavaScript
document.addEventListener('DOMContentLoaded', function() {
const myForm = document.getElementById('myForm');
const emailInput = document.getElementById('email');
const passwordInput = document.getElementById('password');
const validationMessage = document.getElementById('validationMessage');
myForm.addEventListener('submit', function(event) {
event.preventDefault(); // Prevent the default form submission (page reload)
validationMessage.textContent = ''; // Clear previous messages
validationMessage.style.color = 'red';
const email = emailInput.value.trim();
const password = passwordInput.value.trim();
if (email === '' || password === '') {
validationMessage.textContent = 'All fields are required.';
return; // Stop function execution
}
if (!email.includes('@') || !email.includes('.')) {
validationMessage.textContent = 'Please enter a valid email address.';
return;
}
if (password.length < 6) {
validationMessage.textContent = 'Password must be at least 6 characters long.';
return;
}
// If all checks pass
validationMessage.textContent = 'Form submitted successfully!';
validationMessage.style.color = 'green';
// In a real application, you would send this data to a server here
console.log('Form data:', { email, password });
myForm.reset(); // Clear the form fields
});
});
Explanation:
event.preventDefault()
: Stops the browser’s default action for an event (e.g., preventing a form from submitting and reloading the page). Essential for client-side validation.inputElement.value
: Gets or sets the current value of an input field.string.trim()
: Removes whitespace from both ends of a string.string.includes('substring')
: Checks if a string contains a specified substring.string.length
: Gets the length of a string.return;
: Exits the function early if validation fails.myForm.reset()
: Resets all form fields to their initial values.
These examples cover fundamental JavaScript concepts like DOM manipulation, event handling, array processing, and basic form validation. They serve as building blocks for more complex web applications. Practice modifying them, adding new features, and experimenting with different JavaScript methods!