📜

Introduction to JavaScript

Jul 22, 2024

JavaScript Lecture Notes

Introduction to JavaScript

  • JavaScript: A programming language for creating dynamic and interactive web pages.
  • Runs on web browsers (e.g. Chrome, Safari).
  • Responds to user actions and transforms user input.

Key Topics Covered

  1. Text Editor Setup
    • Recommended: VS Code
    • Steps to install covered in HTML/CSS series
  2. Project Setup
    • Create a folder: website
    • Three necessary files: index.html, style.css, index.js
  3. Linking Files
    • HTML to CSS: Use <link> with rel="stylesheet" and href="style.css"
    • HTML to JS: Use <script> with src="index.js" at the bottom of body
    • Live Server Extension: Auto-refresh on file save

Basic Output and Style

  • HTML Elements
    • Example: <h1> for headings
    • Random text: Type lorem in VS Code, then hit TAB.
  • Styling with CSS
    • Change properties in style.css: Example body { font-family: Verdana; }
    • Use CSS selectors like body, h1, p

JavaScript Basics

Console Output

console.log('Hello');
  • Access DevTools: Right-click > Inspect > Console

Alerts

window.alert('This is an alert');
  • Alert boxes for notifications

Comments

  • Single-line comments: // This is a comment
  • Multi-line comments: /* This is a comment */

Selecting HTML Elements

  • By ID: document.getElementById('id')
  • By Class: document.getElementsByClassName('class')
  • By Tag: document.getElementsByTagName('tag')
  • Query Selector: document.querySelector('selector')
  • Query Selector All: Returns node list document.querySelectorAll('selector')

Changing Content and Style

  • Changing Text Content:
document.getElementById('myID').textContent = 'New Text';
  • Changing Style:
const element = document.querySelector('.myClass');
element.style.color = 'red';

Handling Events

Types of Events

  • Click Events
  • Mouse Events (mouseover, mouseout)
  • Keyboard Events (keydown, keyup)

Adding Event Listeners

document.getElementById('myButton').addEventListener('click', function() {
  alert('Button clicked!');
});

Removing Event Listeners

document.getElementById('myButton').removeEventListener('click', myFunction);

Example

document.addEventListener('DOMContentLoaded', function() {
  document.getElementById('myButton').addEventListener('click', function() {
    alert('Button clicked!');
  });
});

Working with Forms

Getting Form Values

const name = document.querySelector('#nameInput').value;

Validating Form Values

if (name === '') {
  alert('Name is required!');
}

Submitting Forms

  • Prevent default behaviour: event.preventDefault();

Advanced JavaScript Topics

Variables and Data Types

let age = 25; // number
eventlistenerconsole.log(typeof age); // number

Functions

  • Function Declarations
function sum(a, b) {
  return a + b;
}
  • Function Expressions
const sum = function(a, b) {
  return a + b;
};
  • Arrow Functions
const sum = (a, b) => a + b;

Objects and Arrays

  • Objects
const person = {
  firstName: 'John',
  lastName: 'Doe',
  age: 30
};
  • Arrays
const fruits = ['apple', 'banana', 'cherry'];

Loops

  • For Loop
for (let i = 0; i < 5; i++) {
  console.log(i);
}
  • While Loop
let i = 0;
while (i < 5) {
  console.log(i);
  i++;
}

Handling Promises

fetch('url')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

Async/Await

const fetchData = async () => {
  try {
    const response = await fetch('url');
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Error:', error);
  }
};
fetchData();