CMU529: Full-Stack Web Development

Session 11: Modern JavaScript Libraries

Duration: 3 hours

Topics: Modern JavaScript libraries, AJAX, DOM manipulation, interactive features

Session Timeline

10 min: Registration & waiting

20 min: Opening slides

45 min: Task 1

15 min: Break/Catch up

20 min: Secondary slides

45 min: Task 2

Remaining: Self-study

Modern JavaScript Overview

Key Areas:

  • ES6+ Features
  • AJAX & Fetch API
  • DOM Manipulation
  • Event Handling
  • Popular Libraries

ES6+ Features

// Arrow Functions
const add = (a, b) => a + b;

// Template Literals
const name = "John";
const greeting = `Hello, ${name}!`;

// Destructuring
const user = { name: "John", age: 30 };
const { name, age } = user;

// Spread Operator
const numbers = [1, 2, 3];
const newNumbers = [...numbers, 4, 5];

// Classes
class User {
  constructor(name) {
    this.name = name;
  }
  greet() {
    return `Hello, ${this.name}!`;
  }
}

AJAX & Fetch API

// Fetch API - GET request
fetch('/api/users')
  .then(response => response.json())
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error('Error:', error);
  });

// POST request
fetch('/api/users', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    name: 'John',
    email: 'john@example.com'
  })
})

Async/Await

// Async function
async function fetchUserData() {
  try {
    const response = await fetch('/api/users/1');
    const user = await response.json();
    return user;
  } catch (error) {
    console.error('Error:', error);
  }
}

// Using the async function
fetchUserData().then(user => {
  console.log(user);
});

DOM Manipulation

// Selecting elements
const element = document.getElementById('myElement');
const elements = document.querySelectorAll('.myClass');

// Creating elements
const newDiv = document.createElement('div');
newDiv.textContent = 'New Element';
newDiv.className = 'new-class';

// Adding to DOM
document.body.appendChild(newDiv);

// Modifying content
element.innerHTML = '<strong>Updated content</strong>';
element.setAttribute('data-id', '123');

Event Handling

// Event listener
document.getElementById('myButton').addEventListener('click', function(e) {
  e.preventDefault();
  console.log('Button clicked!');
});

// Form submission
document.getElementById('myForm').addEventListener('submit', async function(e) {
  e.preventDefault();
  const formData = new FormData(this);
  const data = Object.fromEntries(formData);
  console.log(data);
});

// Keyboard events
document.addEventListener('keydown', function(e) {
  if (e.key === 'Enter') {
    console.log('Enter pressed');
  }
});

Popular JavaScript Libraries

Essential Libraries:

  • jQuery - DOM manipulation & AJAX
  • Lodash - Utility functions
  • Axios - HTTP client
  • Chart.js - Data visualization
  • SweetAlert2 - Beautiful alerts

jQuery Basics

// Include jQuery
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

// Document ready
$(document).ready(function() {
  console.log('jQuery loaded!');
});

// Selecting elements
$('#myElement').hide();
$('.myClass').show();

// AJAX with jQuery
$.ajax({
  url: '/api/data',
  method: 'GET',
  success: function(data) {
    console.log(data);
  }
});

Axios HTTP Client

// Include Axios
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

// GET request
axios.get('/api/users')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });

// POST request
axios.post('/api/users', {
  name: 'John',
  email: 'john@example.com'
})
  .then(response => {
    console.log(response.data);
  });

Chart.js

// Include Chart.js
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

// Create chart
const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['Red', 'Blue', 'Yellow'],
    datasets: [{
      label: 'Sales',
      data: [12, 19, 3],
      backgroundColor: ['red', 'blue', 'yellow']
    }]
  }
});

SweetAlert2

// Include SweetAlert2
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

// Basic alert
Swal.fire('Hello world!');

// Confirmation dialog
Swal.fire({
  title: 'Are you sure?',
  text: "You won't be able to revert this!",
  icon: 'warning',
  showCancelButton: true,
  confirmButtonText: 'Yes, delete it!'
}).then((result) => {
  if (result.isConfirmed) {
    Swal.fire('Deleted!', 'Your file has been deleted.', 'success');
  }
});

Form Validation

// Client-side validation
function validateForm() {
  const email = document.getElementById('email').value;
  const password = document.getElementById('password').value;

  if (!email.includes('@')) {
    alert('Please enter a valid email');
    return false;
  }

  if (password.length < 6) {
    alert('Password must be at least 6 characters');
    return false;
  }

  return true;
}

// Real-time validation
document.getElementById('email').addEventListener('blur', function() {
  if (!this.value.includes('@')) {
    this.style.borderColor = 'red';
  } else {
    this.style.borderColor = 'green';
  }
});

Local Storage

// Store data
localStorage.setItem('user', JSON.stringify({
  name: 'John',
  email: 'john@example.com'
}));

// Retrieve data
const user = JSON.parse(localStorage.getItem('user'));
console.log(user.name); // John

// Remove data
localStorage.removeItem('user');

// Clear all data
localStorage.clear();

// Session storage (temporary)
sessionStorage.setItem('temp', 'temporary data');

Task 1: Interactive Form

Create an interactive contact form:

  • Build a responsive contact form with HTML/CSS
  • Add real-time form validation using JavaScript
  • Implement AJAX form submission using Fetch API
  • Add loading states and success/error messages
  • Use SweetAlert2 for beautiful notifications
  • Store form data in localStorage as backup

Time: 45 minutes

Advanced Features

Additional Advanced Topics:

  • Web APIs (Geolocation, Canvas, WebSocket)
  • Progressive Web Apps (PWA)
  • Service Workers
  • Web Components

Geolocation API

// Get user location
if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(
    function(position) {
      const latitude = position.coords.latitude;
      const longitude = position.coords.longitude;
      console.log(`Lat: ${latitude}, Lng: ${longitude}`);
    },
    function(error) {
      console.error('Error getting location:', error);
    }
  );
} else {
  console.log('Geolocation not supported');
}

Canvas API

// Get canvas context
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');

// Draw shapes
ctx.fillStyle = 'red';
ctx.fillRect(10, 10, 100, 100);

ctx.beginPath();
ctx.arc(200, 60, 50, 0, 2 * Math.PI);
ctx.fillStyle = 'blue';
ctx.fill();

// Draw text
ctx.font = '20px Arial';
ctx.fillStyle = 'black';
ctx.fillText('Hello Canvas!', 10, 150);

Service Workers

// Register service worker
if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/sw.js')
    .then(registration => {
      console.log('SW registered');
    })
    .catch(error => {
      console.log('SW registration failed');
    });
}

// sw.js - Cache files
self.addEventListener('install', event => {
  event.waitUntil(
    caches.open('v1').then(cache => {
      return cache.addAll([
        '/',
        '/styles.css',
        '/script.js'
      ]);
    })
  );
});

Task 2: Interactive Dashboard

Create an interactive dashboard:

  • Build a responsive dashboard layout
  • Integrate Chart.js for data visualization
  • Add real-time data updates using AJAX
  • Implement user preferences with localStorage
  • Add interactive filters and search functionality
  • Create smooth animations and transitions

Time: 45 minutes

Session Summary

Key Takeaways:

  • Modern JavaScript provides powerful features for web development
  • AJAX enables dynamic content without page reloads
  • Popular libraries enhance functionality and user experience
  • Client-side validation improves user interaction
  • Local storage enables offline functionality

Next Session: Final Project Development