Quiz 2
Registry Synced

JavaScript Basics — Making Pages Interactive

924 words
5 min read

Reading compass

Now · 🎯 Learning Objectives

JavaScript Basics — Making Pages Interactive

🎯 Learning Objectives

  • Write JavaScript code and embed it in HTML
  • Manipulate the DOM to change page content
  • Handle user events (click, submit, keypress)
  • Understand functions, scope, and closures
  • Use the Browser Console for debugging

1. What is JavaScript?

JavaScript is the programming language of the web. It runs in the browser and makes web pages interactive. With JavaScript, you can:
  • Change HTML content dynamically
  • Respond to user clicks, keypresses, form submissions
  • Validate form inputs before sending to server
  • Fetch data from servers without reloading the page

2. Embedding JavaScript

html
<!-- Inline (within HTML) -->
<script>
    alert('Hello!');
</script>
<!-- External file (best practice) -->
<script src="script.js"></script>
<!-- At end of body (recommended for performance) -->
<body>
    <!-- HTML content -->
    <script src="js/app.js"></script>
</body>

3. Basic Syntax

javascript
// Variables
let name = 'Alice';          // Mutable, block-scoped
const PI = 3.14159;          // Immutable reference
var old = 'avoid this';      // Function-scoped, can be redeclared
// Data types
let number = 42;
let text = "Hello";
let isTrue = true;
let list = [1, 2, 3];
let person = { name: 'Alice', age: 25 };
// Functions
function greet(name) {
    return `Hello, ${name}!`;
}
// Arrow function (ES6)
const add = (a, b) => a + b;
// Conditionals
if (age >= 18) {
    console.log('Adult');
} else {
    console.log('Minor');
}
// Loops
for (let i = 0; i < 5; i++) {
    console.log(i);
}
for (let item of list) {
    console.log(item);
}

4. DOM Manipulation

The DOM (Document Object Model) is a tree representation of the HTML page.
javascript
// Selecting elements
document.getElementById('header');            // By ID (fastest)
document.querySelector('.highlight');        // First match (CSS selector)
document.querySelectorAll('.item');          // All matches (NodeList)
document.getElementsByClassName('item');     // By class (HTMLCollection)
document.getElementsByTagName('div');        // By tag name
// Changing content
const header = document.getElementById('header');
header.textContent = 'New Title';            // Change text (safe)
header.innerHTML = '<span>New Title</span>'; // Change HTML (careful with XSS)
// Changing styles
header.style.color = 'blue';
header.style.backgroundColor = '#f0f0f0';
header.classList.add('highlight');           // Add CSS class
header.classList.remove('inactive');         // Remove CSS class
header.classList.toggle('active');           // Toggle CSS class
// Creating and adding elements
const newItem = document.createElement('li');
newItem.textContent = 'Item 3';
document.getElementById('list').appendChild(newItem);
// Removing elements
element.remove();                            // Modern way
parent.removeChild(child);                   // Older way

5. Event Handling

javascript
// Basic click event
document.getElementById('myButton').addEventListener('click', function(event) {
    console.log('Button clicked!');
    console.log(event.target);  // The element that was clicked
});
// Form submission
document.getElementById('myForm').addEventListener('submit', function(event) {
    event.preventDefault();  // Stop page reload
    const name = document.getElementById('name').value;
    console.log('Submitted:', name);
});
// Common events
element.addEventListener('click', handler);    // Mouse click
element.addEventListener('mouseover', handler); // Mouse enters
element.addEventListener('mouseout', handler);  // Mouse leaves
element.addEventListener('keydown', handler);   // Key pressed
element.addEventListener('keyup', handler);     // Key released
element.addEventListener('change', handler);    // Input value changed
element.addEventListener('input', handler);     // Input value changes (real-time)

6. Working with Forms

javascript
document.getElementById('loginForm').addEventListener('submit', function(e) {
    e.preventDefault();
    const username = document.getElementById('username').value.trim();
    const password = document.getElementById('password').value;
    const errors = [];
    // Validation
    if (username.length < 3) {
        errors.push('Username must be at least 3 characters');
    }
    if (password.length < 6) {
        errors.push('Password must be at least 6 characters');
    }
    if (errors.length > 0) {
        document.getElementById('errors').innerHTML =
            errors.map(e => `<li>${e}</li>`).join('');
    } else {
        // Send to server (AJAX)
        console.log('Submitting:', { username, password });
    }
});

7. Debugging with Browser Console

javascript
console.log('Regular message');           // General logging
console.error('Error message');           // Red error
console.warn('Warning message');          // Yellow warning
console.table([{a:1, b:2}, {a:3, b:4}]); // Table format
console.time('label');                    // Start timer
// ... code ...
console.timeEnd('label');                 // End timer: prints duration

8. Practice Questions

Q1: How do you select an element by its ID?
Answer: document.getElementById('myId') or document.querySelector('#myId'). getElementById is faster; querySelector is more flexible. Q2: What does event.preventDefault() do?
Answer: Prevents the browser's default behavior for that event. Most commonly used with form submissions to stop the page from reloading. Also used with anchor tags to prevent navigation. Q3: What's the difference between textContent and innerHTML?
Answer: textContent sets plain text (safe, automatically escapes HTML). innerHTML sets HTML content (can render formatting but is a security risk if content includes user input — XSS vulnerability). Q4: How do you add a CSS class to an element?
Answer: element.classList.add('className'), remove('className'), toggle('className'), or element.className = 'class1 class2' (replaces all classes). Q5: How do you create a new element and add it to the page?
Answer:
javascript
const div = document.createElement('div');
div.textContent = 'New element';
document.body.appendChild(div);
Q6: What is the difference between let and const?
Answer: let can be reassigned (let x = 1; x = 2;). const cannot be reassigned (const y = 1; y = 2; throws TypeError). However, const objects can have their properties modified. Q7: How do you handle multiple elements with the same class?
Answer: document.querySelectorAll('.className') returns a NodeList (array-like). Iterate with forEach or a for loop. Q8: Write JavaScript to validate that a form field is not empty.
javascript
document.getElementById('myForm').addEventListener('submit', function(e) {
    e.preventDefault();
    const value = document.getElementById('name').value.trim();
    if (value === '') {
        document.getElementById('error').textContent = 'Name is required';
    } else {
        document.getElementById('error').textContent = '';
        console.log('Valid:', value);
    }
});

📐 Key Concepts

ConceptCodePurpose
Select elementdocument.querySelector()Find element in DOM
Change textelement.textContent = '...'Update content
Styleelement.style.color = 'red'Change appearance
Add classelement.classList.add('c')Apply CSS class
Eventelement.addEventListener()Handle interactions
Prevent defaulte.preventDefault()Stop browser default
Form valueinput.valueGet input content

🔗 Cross-References

Document outline

Keep your place and jump directly to a heading.

Table of Contents
System Normal // Awaiting Context

Intelligence Hub

Navigate the knowledge graph to generate context. The Hub adapts dynamically to surface backlinks, related notes, and metadata insights.