Neural Sync Active
JavaScript Basics — Making Pages Interactive
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
javascriptdocument.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
javascriptconsole.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')ordocument.querySelector('#myId'). getElementById is faster; querySelector is more flexible. Q2: What doesevent.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 betweentextContentandinnerHTML?Answer:textContentsets plain text (safe, automatically escapes HTML).innerHTMLsets 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'), orelement.className = 'class1 class2'(replaces all classes). Q5: How do you create a new element and add it to the page?Answer:javascriptconst div = document.createElement('div'); div.textContent = 'New element'; document.body.appendChild(div);Q6: What is the difference betweenletandconst?Answer:letcan be reassigned (let x = 1; x = 2;).constcannot be reassigned (const y = 1; y = 2;throws TypeError). However,constobjects 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 withforEachor a for loop. Q8: Write JavaScript to validate that a form field is not empty.javascriptdocument.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
| Concept | Code | Purpose |
|---|---|---|
| Select element | document.querySelector() | Find element in DOM |
| Change text | element.textContent = '...' | Update content |
| Style | element.style.color = 'red' | Change appearance |
| Add class | element.classList.add('c') | Apply CSS class |
| Event | element.addEventListener() | Handle interactions |
| Prevent default | e.preventDefault() | Stop browser default |
| Form value | input.value | Get input content |