Assignments Of Day 28: JavaScript for Web Development: SPA

Rashmi Mishra
0

 Assignments Of  Day 28: JavaScript for Web Development: SPA

Assignment 1: Basic SPA Routing

Problem Statement:

Create a basic SPA that includes two pages: "Home" and "Contact". The Home page should display "Welcome to the Home Page" and the Contact page should display "Contact Us". Use JavaScript to handle the routing without refreshing the page.

Solution:

HTML:

html

Copy code

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>SPA Example</title>

</head>

<body>

    <nav>

        <a href="#home" class="nav-link">Home</a>

        <a href="#contact" class="nav-link">Contact</a>

    </nav>

   

    <div id="content">

        <h1>Welcome to our SPA</h1>

    </div>

 

    <script src="spa.js"></script>

</body>

</html>

JavaScript (spa.js):

javascript

Copy code

// Function to load content based on the page

function loadPage(page) {

    const contentDiv = document.getElementById('content');

   

    if (page === 'home') {

        contentDiv.innerHTML = "<h1>Welcome to the Home Page</h1>";

    } else if (page === 'contact') {

        contentDiv.innerHTML = "<h1>Contact Us</h1><p>Email us at: contact@example.com</p>";

    }

}

 

// Handle link clicks

function handleLinkClick(event, page) {

    event.preventDefault(); // Prevent page reload

    history.pushState({ page: page }, page, `/${page}`); // Change URL without page reload

    loadPage(page); // Load content dynamically

}

 

// Event listeners for link clicks

document.querySelectorAll('.nav-link').forEach(link => {

    link.addEventListener('click', (event) => {

        handleLinkClick(event, link.getAttribute('href').substring(1)); // Extract page name

    });

});

 

// Handle back/forward navigation

window.addEventListener('popstate', (event) => {

    if (event.state) {

        loadPage(event.state.page);

    }

});

Explanation:

  • The links prevent the default behavior and load the appropriate content when clicked.
  • history.pushState() updates the URL while avoiding page refreshes.
  • The popstate event listens for browser back and forward actions to load the correct content.

Assignment 2: Dynamic Content Loading with Fetch API

Problem Statement:

Create a simple SPA that fetches content from a JSON file. The JSON file should contain content for two pages: "Home" and "About". Dynamically load the content of the "Home" and "About" pages when the respective links are clicked.

Solution:

HTML:

html

Copy code

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>SPA with Fetch</title>

</head>

<body>

    <nav>

        <a href="#home" class="nav-link">Home</a>

        <a href="#about" class="nav-link">About</a>

    </nav>

   

    <div id="content">

        <h1>Welcome to our SPA</h1>

    </div>

 

    <script src="spa-fetch.js"></script>

</body>

</html>

JavaScript (spa-fetch.js):

javascript

Copy code

// Fetch and load content dynamically

function loadContent(page) {

    fetch(`${page}.json`)

        .then(response => response.json())

        .then(data => {

            const contentDiv = document.getElementById('content');

            contentDiv.innerHTML = `<h1>${data.title}</h1><p>${data.body}</p>`;

        })

        .catch(error => {

            console.log('Error loading content:', error);

        });

}

 

// Handle link clicks

function handleLinkClick(event, page) {

    event.preventDefault(); // Prevent page reload

    history.pushState({ page: page }, page, `/${page}`); // Update URL

    loadContent(page); // Fetch and load the content dynamically

}

 

// Event listeners for link clicks

document.querySelectorAll('.nav-link').forEach(link => {

    link.addEventListener('click', (event) => {

        handleLinkClick(event, link.getAttribute('href').substring(1)); // Extract page name

    });

});

 

// Handle back/forward navigation

window.addEventListener('popstate', (event) => {

    if (event.state) {

        loadContent(event.state.page);

    }

});

Sample JSON for Home (home.json):

json

Copy code

{

    "title": "Welcome to the Home Page",

    "body": "This content is dynamically loaded using JavaScript!"

}

Sample JSON for About (about.json):

json

Copy code

{

    "title": "About Us",

    "body": "We are a team of developers learning JavaScript and building SPAs!"

}

Explanation:

  • The fetch() function is used to load content from a JSON file when the user clicks on the link.
  • The JSON content is dynamically inserted into the webpage.

Assignment 3: Adding More Pages to the SPA

Problem Statement:

Extend the previous SPA to include three pages: "Home", "About", and "Services". Use JavaScript to handle the routing and dynamically load content for each page.

Solution:

HTML:

html

Copy code

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>SPA with Multiple Pages</title>

</head>

<body>

    <nav>

        <a href="#home" class="nav-link">Home</a>

        <a href="#about" class="nav-link">About</a>

        <a href="#services" class="nav-link">Services</a>

    </nav>

   

    <div id="content">

        <h1>Welcome to our SPA</h1>

    </div>

 

    <script src="spa-multi.js"></script>

</body>

</html>

JavaScript (spa-multi.js):

javascript

Copy code

// Function to load content dynamically from JSON files

function loadContent(page) {

    fetch(`${page}.json`)

        .then(response => response.json())

        .then(data => {

            const contentDiv = document.getElementById('content');

            contentDiv.innerHTML = `<h1>${data.title}</h1><p>${data.body}</p>`;

        })

        .catch(error => {

            console.log('Error loading content:', error);

        });

}

 

// Handle link clicks

function handleLinkClick(event, page) {

    event.preventDefault(); // Prevent page reload

    history.pushState({ page: page }, page, `/${page}`); // Update URL

    loadContent(page); // Load content dynamically

}

 

// Event listeners for link clicks

document.querySelectorAll('.nav-link').forEach(link => {

    link.addEventListener('click', (event) => {

        handleLinkClick(event, link.getAttribute('href').substring(1)); // Pass page name

    });

});

 

// Handle back/forward navigation

window.addEventListener('popstate', (event) => {

    if (event.state) {

        loadContent(event.state.page);

    }

});

Sample JSON for Home (home.json):

json

Copy code

{

    "title": "Welcome to the Home Page",

    "body": "This is the home page of our SPA!"

}

Sample JSON for About (about.json):

json

Copy code

{

    "title": "About Us",

    "body": "This page contains information about us!"

}

Sample JSON for Services (services.json):

json

Copy code

{

    "title": "Our Services",

    "body": "We provide top-notch JavaScript and web development services!"

}

Explanation:

  • This example expands the SPA to include three pages, each dynamically loaded from their respective JSON files.
  • The routing system continues to work with history.pushState() and popstate for browser navigation.

Assignment 4: Dynamic Navigation Links Based on Content

Problem Statement:

Create a SPA where the navigation links are generated dynamically based on the JSON data. The links should allow the user to navigate between "Home", "About", and "Services" pages, and the content should be loaded dynamically.

Solution:

HTML:

html

Copy code

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Dynamic Navigation</title>

</head>

<body>

    <nav id="navigation"></nav>

   

    <div id="content">

        <h1>Welcome to our SPA</h1>

    </div>

 

    <script src="dynamic-nav.js"></script>

</body>

</html>

JavaScript (dynamic-nav.js):

javascript

Copy code

// Sample JSON for pages

const pages = [

    { "name": "Home", "url": "home" },

    { "name": "About", "url": "about" },

    { "name": "Services", "url": "services" }

];

 

// Generate navigation links dynamically

function generateNav() {

    const nav = document.getElementById('navigation');

    pages.forEach(page => {

        const link = document.createElement('a');

        link.href = `#${page.url}`;

        link.textContent = page.name;

        link.classList.add('nav-link');

        nav.appendChild(link);

    });

}

 

// Function to load content dynamically from JSON files

function loadContent(page) {

    fetch(`${page}.json`)

        .then(response => response.json())

        .then(data => {

            const contentDiv = document.getElementById('content');

            contentDiv.innerHTML = `<h1>${data.title}</h1><p>${data.body}</p>`;

        })

        .catch(error => {

            console.log('Error loading content:', error);

        });

}

 

// Handle link clicks

function handleLinkClick(event, page) {

    event.preventDefault(); // Prevent page reload

    history.pushState({ page: page }, page, `/${page}`); // Update URL

    loadContent(page); // Load content dynamically

}

 

// Event listeners for link clicks

document.addEventListener('DOMContentLoaded', () => {

    generateNav(); // Generate navigation when content is loaded

 

    document.querySelectorAll('.nav-link').forEach(link => {

        link.addEventListener('click', (event) => {

            handleLinkClick(event, link.getAttribute('href').substring(1)); // Pass page name

        });

    });

 

    // Initial content load

    loadContent('home');

});

 

// Handle back/forward navigation

window.addEventListener('popstate', (event) => {

    if (event.state) {

        loadContent(event.state.page);

    }

});


These assignments should help students get comfortable with dynamic routing, content loading, and handling SPAs with JavaScript.

4o mini

You said:

give more

ChatGPT said:

ChatGPT

Here are additional assignments based on the JavaScript for Web Development: SPA concept:


Assignment 5: Implementing an SPA with a Search Feature

Problem Statement:

Create an SPA that allows the user to search for content on different pages ("Home", "About", and "Services"). The search should dynamically display results from the respective page content without reloading the page. The search input should be displayed on the Home page and used to search across the pages.

Solution:

HTML:

html

Copy code

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>SPA with Search</title>

</head>

<body>

    <nav>

        <a href="#home" class="nav-link">Home</a>

        <a href="#about" class="nav-link">About</a>

        <a href="#services" class="nav-link">Services</a>

    </nav>

 

    <div id="content">

        <input type="text" id="search-input" placeholder="Search..." onkeyup="searchContent()">

        <div id="page-content">

            <h1>Welcome to our SPA</h1>

        </div>

    </div>

 

    <script src="spa-search.js"></script>

</body>

</html>

JavaScript (spa-search.js):

javascript

Copy code

// Content for pages

const pageContent = {

    home: "This is the home page where we talk about our website.",

    about: "This is the about page where we discuss our goals and values.",

    services: "This page lists the services we offer, including web development and design."

};

 

// Load content based on the page

function loadContent(page) {

    const contentDiv = document.getElementById('page-content');

    contentDiv.innerHTML = `<p>${pageContent[page]}</p>`;

}

 

// Handle link clicks and change the URL without refreshing

function handleLinkClick(event, page) {

    event.preventDefault();

    history.pushState({ page: page }, page, `/${page}`);

    loadContent(page);

}

 

// Handle search input and display matching results

function searchContent() {

    const searchTerm = document.getElementById('search-input').value.toLowerCase();

    const result = Object.values(pageContent).filter(content => content.toLowerCase().includes(searchTerm));

    const contentDiv = document.getElementById('page-content');

    contentDiv.innerHTML = result.length > 0 ? result.join("<br><br>") : "No results found";

}

 

// Event listeners for navigation

document.querySelectorAll('.nav-link').forEach(link => {

    link.addEventListener('click', (event) => {

        handleLinkClick(event, link.getAttribute('href').substring(1));

    });

});

 

// Initial content load

window.addEventListener('load', () => {

    loadContent('home');

});

 

// Handle back/forward navigation

window.addEventListener('popstate', (event) => {

    if (event.state) {

        loadContent(event.state.page);

    }

});

Explanation:

  • This assignment adds a search feature to the SPA.
  • The user can type in the search box, and the content of the page is dynamically filtered based on the search term.
  • The content for each page is stored in an object and displayed dynamically.

Assignment 6: SPA with Form Handling

Problem Statement:

Build an SPA that includes a simple form on the "Contact" page. The form should allow the user to enter their name and email. When the form is submitted, the data should be displayed below the form on the same page without refreshing the page.

Solution:

HTML:

html

Copy code

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>SPA with Form</title>

</head>

<body>

    <nav>

        <a href="#home" class="nav-link">Home</a>

        <a href="#contact" class="nav-link">Contact</a>

    </nav>

   

    <div id="content">

        <div id="page-content">

            <h1>Welcome to our SPA</h1>

        </div>

    </div>

 

    <script src="spa-form.js"></script>

</body>

</html>

JavaScript (spa-form.js):

javascript

Copy code

// Function to load content based on the page

function loadContent(page) {

    const contentDiv = document.getElementById('page-content');

   

    if (page === 'home') {

        contentDiv.innerHTML = "<h1>Welcome to the Home Page</h1><p>This is the homepage of our SPA.</p>";

    } else if (page === 'contact') {

        contentDiv.innerHTML = `

            <h1>Contact Us</h1>

            <form id="contact-form">

                <input type="text" id="name" placeholder="Enter your name" required>

                <input type="email" id="email" placeholder="Enter your email" required>

                <button type="submit">Submit</button>

            </form>

            <div id="form-data"></div>

        `;

        document.getElementById('contact-form').addEventListener('submit', handleSubmit);

    }

}

 

// Handle form submission

function handleSubmit(event) {

    event.preventDefault();

   

    const name = document.getElementById('name').value;

    const email = document.getElementById('email').value;

 

    const formDataDiv = document.getElementById('form-data');

    formDataDiv.innerHTML = `<p>Submitted Data:</p><p>Name: ${name}</p><p>Email: ${email}</p>`;

 

    // Clear the form fields

    document.getElementById('contact-form').reset();

}

 

// Handle link clicks

function handleLinkClick(event, page) {

    event.preventDefault();

    history.pushState({ page: page }, page, `/${page}`);

    loadContent(page);

}

 

// Event listeners for link clicks

document.querySelectorAll('.nav-link').forEach(link => {

    link.addEventListener('click', (event) => {

        handleLinkClick(event, link.getAttribute('href').substring(1));

    });

});

 

// Initial content load

window.addEventListener('load', () => {

    loadContent('home');

});

 

// Handle back/forward navigation

window.addEventListener('popstate', (event) => {

    if (event.state) {

        loadContent(event.state.page);

    }

});

Explanation:

  • This SPA includes a form on the "Contact" page.
  • When the form is submitted, the data entered is displayed below the form without refreshing the page.
  • The handleSubmit() function prevents the page reload and displays the submitted data dynamically.

Assignment 7: Implementing a "Back to Top" Button in an SPA

Problem Statement:

Create a "Back to Top" button that becomes visible when the user scrolls down the page. The button should allow the user to scroll back to the top of the page when clicked, without reloading the page.

Solution:

HTML:

html

Copy code

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>SPA with Back to Top</title>

</head>

<body>

    <nav>

        <a href="#home" class="nav-link">Home</a>

        <a href="#about" class="nav-link">About</a>

        <a href="#services" class="nav-link">Services</a>

    </nav>

 

    <div id="content">

        <div id="page-content">

            <h1>Welcome to our SPA</h1>

            <p>Scroll down to see the "Back to Top" button.</p>

            <div style="height: 1500px;"></div> <!-- Added for scrolling -->

        </div>

    </div>

 

    <button id="backToTop" onclick="scrollToTop()">Back to Top</button>

 

    <script src="spa-back-to-top.js"></script>

</body>

</html>

JavaScript (spa-back-to-top.js):

javascript

Copy code

// Function to load content based on the page

function loadContent(page) {

    const contentDiv = document.getElementById('page-content');

   

    if (page === 'home') {

        contentDiv.innerHTML = "<h1>Welcome to the Home Page</h1><p>This is the homepage of our SPA. Scroll down to see the button.</p>";

    } else if (page === 'about') {

        contentDiv.innerHTML = "<h1>About Us</h1><p>We provide high-quality web development services.</p>";

    } else if (page === 'services') {

        contentDiv.innerHTML = "<h1>Our Services</h1><p>We specialize in front-end and back-end web development.</p>";

    }

}

 

// Handle link clicks

function handleLinkClick(event, page) {

    event.preventDefault();

    history.pushState({ page: page }, page, `/${page}`);

    loadContent(page);

}

 

// Handle scroll event to show/hide "Back to Top" button

window.onscroll = function() {

    const backToTopButton = document.getElementById('backToTop');

    if (document.body.scrollTop > 200 || document.documentElement.scrollTop > 200) {

        backToTopButton.style.display = "block";

    } else {

        backToTopButton.style.display = "none";

    }

};

 

// Function to scroll back to top

function scrollToTop() {

    document.body.scrollTop = 0;

    document.documentElement.scrollTop = 0;

}

 

// Event listeners for link clicks

document.querySelectorAll('.nav-link').forEach(link => {

    link.addEventListener('click', (event) => {

        handleLinkClick(event, link.getAttribute('href').substring(1));

    });

});

 

// Initial content load

window.addEventListener('load', () => {

    loadContent('home');

});

 

// Handle back/forward navigation

window.addEventListener('popstate', (event) => {

    if (event.state) {

        loadContent(event.state.page);

    }

});

Explanation:

  • This SPA includes a "Back to Top" button that appears when the user scrolls down 200px.
  • The button scrolls the page back to the top when clicked.
  • The onscroll event listener dynamically toggles the visibility of the button.

These assignments should provide students with practice on various SPA features such as form handling, dynamic content loading, and adding interactive elements like the "Back to Top" button.

4o mini

You said:

give more

ChatGPT said:

ChatGPT

Here are more assignments based on JavaScript for Web Development: SPA concepts:


Assignment 8: SPA with Dynamic Content Based on URL Hash

Problem Statement:

Create an SPA where the content dynamically changes based on the URL hash. When the user clicks on the navigation links, the URL hash changes to represent the selected page, and the corresponding content is displayed without refreshing the page.

Solution:

HTML:

html

Copy code

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>SPA with URL Hash</title>

</head>

<body>

    <nav>

        <a href="#home" class="nav-link">Home</a>

        <a href="#about" class="nav-link">About</a>

        <a href="#services" class="nav-link">Services</a>

    </nav>

   

    <div id="content">

        <div id="page-content">

            <h1>Welcome to our SPA</h1>

            <p>Select a page from the navigation.</p>

        </div>

    </div>

 

    <script src="spa-url-hash.js"></script>

</body>

</html>

JavaScript (spa-url-hash.js):

javascript

Copy code

// Content for each page

const pageContent = {

    home: "<h1>Home Page</h1><p>Welcome to the homepage.</p>",

    about: "<h1>About Us</h1><p>Learn about our company and mission.</p>",

    services: "<h1>Our Services</h1><p>We offer web development, design, and consulting services.</p>"

};

 

// Function to load content based on the current URL hash

function loadContent() {

    const page = window.location.hash.substring(1) || 'home'; // Default to home

    const contentDiv = document.getElementById('page-content');

    contentDiv.innerHTML = pageContent[page] || "<h1>Page not found</h1>";

}

 

// Event listener for URL hash change

window.addEventListener('hashchange', loadContent);

 

// Initial content load based on URL hash

window.addEventListener('load', loadContent);

Explanation:

  • The content of the page changes based on the URL hash (e.g., #home, #about, #services).
  • When the user clicks a navigation link, the URL hash updates, and the corresponding content is displayed without reloading the page.
  • The hashchange event is used to listen for changes in the hash part of the URL and update the page content accordingly.

Assignment 9: Simple SPA with Dark/Light Theme Toggle

Problem Statement:

Create a simple SPA with a toggle button to switch between dark and light themes. The theme should persist even if the user navigates to different pages within the SPA.

Solution:

HTML:

html

Copy code

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>SPA with Theme Toggle</title>

    <link rel="stylesheet" href="styles.css">

</head>

<body>

    <nav>

        <a href="#home" class="nav-link">Home</a>

        <a href="#about" class="nav-link">About</a>

        <a href="#services" class="nav-link">Services</a>

        <button id="theme-toggle">Toggle Theme</button>

    </nav>

 

    <div id="content">

        <div id="page-content">

            <h1>Welcome to our SPA</h1>

            <p>Click the theme toggle to switch between dark and light modes.</p>

        </div>

    </div>

 

    <script src="spa-theme-toggle.js"></script>

</body>

</html>

CSS (styles.css):

css

Copy code

/* Light Theme */

body {

    background-color: white;

    color: black;

    font-family: Arial, sans-serif;

}

 

nav {

    background-color: lightgray;

    padding: 10px;

}

 

/* Dark Theme */

body.dark-theme {

    background-color: #121212;

    color: white;

}

 

nav.dark-theme {

    background-color: #333;

}

 

button {

    padding: 10px;

    margin-left: 20px;

    cursor: pointer;

}

JavaScript (spa-theme-toggle.js):

javascript

Copy code

// Load content based on the hash value

function loadContent() {

    const page = window.location.hash.substring(1) || 'home'; // Default to home

    const contentDiv = document.getElementById('page-content');

   

    if (page === 'home') {

        contentDiv.innerHTML = "<h1>Home Page</h1><p>Welcome to our homepage.</p>";

    } else if (page === 'about') {

        contentDiv.innerHTML = "<h1>About Us</h1><p>Learn more about our mission.</p>";

    } else if (page === 'services') {

        contentDiv.innerHTML = "<h1>Our Services</h1><p>We offer web design and development services.</p>";

    } else {

        contentDiv.innerHTML = "<h1>Page not found</h1>";

    }

}

 

// Theme toggle function

function toggleTheme() {

    document.body.classList.toggle('dark-theme');

    document.querySelector('nav').classList.toggle('dark-theme');

    localStorage.setItem('theme', document.body.classList.contains('dark-theme') ? 'dark' : 'light');

}

 

// Set the theme based on the saved preference

window.addEventListener('load', () => {

    if (localStorage.getItem('theme') === 'dark') {

        document.body.classList.add('dark-theme');

        document.querySelector('nav').classList.add('dark-theme');

    }

 

    loadContent();

   

    // Theme toggle button

    document.getElementById('theme-toggle').addEventListener('click', toggleTheme);

});

 

// Handle hash changes

window.addEventListener('hashchange', loadContent);

Explanation:

  • This SPA includes a theme toggle button that allows the user to switch between light and dark themes.
  • The theme preference is saved in localStorage, so it persists even after page reloads.
  • The toggleTheme() function toggles the dark-theme class on the body and the navigation bar to apply the styles.

Assignment 10: SPA with Dynamic Page Loading (AJAX Simulation)

Problem Statement:

Build an SPA where the content for each page is fetched dynamically when the user clicks on the navigation links. The content should be fetched via an AJAX call, simulating a real-world API request.

Solution:

HTML:

html

Copy code

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>SPA with AJAX</title>

</head>

<body>

    <nav>

        <a href="#home" class="nav-link">Home</a>

        <a href="#about" class="nav-link">About</a>

        <a href="#services" class="nav-link">Services</a>

    </nav>

   

    <div id="content">

        <div id="page-content">

            <h1>Welcome to our SPA</h1>

            <p>Select a page from the navigation to load content dynamically.</p>

        </div>

    </div>

 

    <script src="spa-ajax.js"></script>

</body>

</html>

JavaScript (spa-ajax.js):

javascript

Copy code

// Simulated AJAX content

const pageContent = {

    home: "<h1>Home Page</h1><p>This is the homepage content, fetched dynamically.</p>",

    about: "<h1>About Us</h1><p>This is the about page content, fetched dynamically.</p>",

    services: "<h1>Our Services</h1><p>This is the services page content, fetched dynamically.</p>"

};

 

// Simulate an AJAX request to fetch page content

function fetchPageContent(page) {

    return new Promise((resolve) => {

        setTimeout(() => {

            resolve(pageContent[page] || "<h1>Page not found</h1>");

        }, 500); // Simulate a delay

    });

}

 

// Function to load content based on the page

function loadContent() {

    const page = window.location.hash.substring(1) || 'home';

    const contentDiv = document.getElementById('page-content');

   

    // Simulate AJAX request

    fetchPageContent(page).then(content => {

        contentDiv.innerHTML = content;

    });

}

 

// Handle link clicks

function handleLinkClick(event, page) {

    event.preventDefault();

    history.pushState({ page: page }, page, `/${page}`);

    loadContent();

}

 

// Event listeners for link clicks

document.querySelectorAll('.nav-link').forEach(link => {

    link.addEventListener('click', (event) => {

        handleLinkClick(event, link.getAttribute('href').substring(1));

    });

});

 

// Initial content load

window.addEventListener('load', loadContent);

 

// Handle back/forward navigation

window.addEventListener('popstate', (event) => {

    if (event.state) {

        loadContent();

    }

});

Explanation:

  • The fetchPageContent() function simulates an AJAX call, loading content after a short delay.
  • When a navigation link is clicked, the loadContent() function is triggered, fetching and displaying the content dynamically.
  • The URL is updated using history.pushState() without reloading the page, allowing for proper back and forward navigation.

These assignments focus on key SPA features such as content loading based on URL changes, dynamic content fetching (simulated AJAX), theme switching, and handling navigation without page reloads.

Post a Comment

0Comments

Post a Comment (0)