0

When I click on the link i want page2.html to appear without any reloading of the current page. Despite all trials, when i click on the link it does reload the entire page before displaying page2.html

<script> $(document).ready(function() { $("a").click(function(event) { var $this = $(this), url = $this.data("url"); $(document.body).load(url); event.preventDefault(); }); }); < /script>

homepage.html

<a href="#" data-url="page2.html" class="topic-list-item"> <h3 class="topic-title">Internet Protocol Basics</h3> <div class="topic-description-text"> Learn how Internet Protocol is used </div> </a>

5
  • function(data) should be something like function(data){ $('.myDiv').html(data)} Commented Nov 3, 2015 at 14:06
  • do you want to replace full html or just the content of div Commented Nov 3, 2015 at 14:08
  • @Virendrayadav the full html... i want page1 to be replaced by page2 but without reload Commented Nov 3, 2015 at 14:11
  • @DLeh still doesn't work Commented Nov 3, 2015 at 14:20
  • $("a").click(function(){ return false;... Commented Nov 3, 2015 at 14:23

3 Answers 3

0

Set Up the Stream Progress Bar

<div class="progress-bar-container"> <div class="progress-bar"></div> </div> 

Implementing JavaScript Routes :

document.addEventListener("DOMContentLoaded", function () { const progressBar = document.getElementById("progress-bar"); // Update the progress bar width based on the loading percentage function updateProgressBar(percentage) { progressBar.style.width = `${percentage}%`; progressBar.classList.add("filled"); // hide progress bar when content is loaded if (percentage == 100) { setTimeout(() => { progressBar.classList.remove("filled"); progressBar.style.width = 0; }, 300); } } // Fetch content based on the URL and update the page function fetchContent(url) { updateProgressBar(0); // Reset progress bar console.log(url); fetch(url, { headers: { "Content-Type": "text/html; charset=utf-8", }, mode: "cors", }) .then((response) => { const reader = response.body.getReader(); const decoder = new TextDecoder("utf-8"); const total = +response.headers.get("Content-Length"); let loaded = 0; let html = ""; function read() { reader.read().then(({ done, value }) => { if (done) { const parser = new DOMParser(); const doc = parser.parseFromString(html, "text/html"); // Extract the specific HTML element and their child's from the parsed document const primary = doc.querySelector("#primary"); // take content element from current page const appContainer = document.getElementById("content"); // Then, Remove all child elements while (appContainer.firstChild) { appContainer.removeChild(appContainer.firstChild); } // Append a new element appContainer.appendChild(primary); updateProgressBar(100); // Set progress bar to 100% when content is loaded return; } loaded += value.length; updateProgressBar((loaded / total) * 100); const chunk = decoder.decode(value, { stream: true }); html += chunk; // Process the content here if needed // somthing like pelase wait or spinner.. read(); // Continue reading the stream }); } read(); }) .catch((error) => { console.error(error); updateProgressBar(0); // Reset progress bar in case of errors }); } // Handle link clicks function handleLinkClick(event) { const target = event.target; // Check if the clicked element or its parent is an anchor element const anchor = target.closest("a"); if (anchor) { event.preventDefault(); // Get the href attribute of the anchor element const targetUrl = anchor.getAttribute("href"); // Update the URL and push a new history state history.pushState(null, "", targetUrl); // Fetch and load the content for the clicked link fetchContent(targetUrl); } } // Attach click event listeners to all links const allLinks = document.querySelectorAll("a"); allLinks.forEach((link) => { link.addEventListener("click", handleLinkClick); }); // Handle the popstate event to update the page when the user navigates back/forward window.addEventListener("popstate", () => { fetchContent(window.location.href); }); }); 

In the above code, we first attach an event listener to the DOMContentLoaded event to ensure our JavaScript code runs when the page has finished loading.

The handleLinkClick function is responsible for intercepting link clicks, preventing the default behavior, starting the progress bar animation, and fetching the content for the clicked link using the fetchContent function.

The fetchContent function sends a GET request to the target URL, retrieves the response as text, stops the progress bar animation, and updates the content container with the fetched HTML.

Make sure to have a CSS file linked to your HTML, where you can define the styles for the progress bar animation. Here's a basic CSS example for the progress bar:

.progress-bar-container { width: 100%; height: 2px; background-color: transparent; position: absolute; top: 0; display: block; } .progress-bar { width: 0; height: 100%; background-color: #f00; position: relative; transition: width 0.3s ease-in-out; opacity: 0; } .progress-bar.filled { opacity: 1; } /* Optional: Add animation to the progress bar */ @keyframes progress-animation { 0% { width: 0; } 100% { width: 100%; } } 

Feel free to customize the CSS styles to match your website's design.

Sign up to request clarification or add additional context in comments.

Comments

-1
$("a").click(function() { var $this = $(this), href = $this.attr("href"); $(document.body).load(href); location.href = "#" + href; }); 

See jQuery.fn.load for more details.

4 Comments

But I have 10 such link, will i have to repeat this code 10 times ?
try removing this part location.href = "#" + href;
@MancharyManchaary still no.
Give credit to the answer you copy-pasted. stackoverflow.com/a/11601219/7383506
-1

try this code it will work

$(document).ready(function () { $("a").click(function (event) { var $this = $(this), url = $this.data("url"); $(document.body).load(url); event.preventDefault(); }); }); 

the problem with Digital's code is that he is not using data function to get url as well when we click on then default action for anchor will be called so we need to stop default action so i used event.preventDefault();

also always put your jquery code between $(document).ready block

4 Comments

I really don't understand why it is not working. page2.html is not opening.
i created a a demo on local system, it is working fine
you can see in console to check any javascript related error , is your jquery properly added in your page
<!Doctype html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script> $(document).ready(function () { $("a").click(function (event) { var $this = $(this), url = $this.data("url"); $(document.body).load(url); event.preventDefault(); }); }); </script> </head> <body> <a href="#" data-url="new.html">Internet Protocol Basics</a> </body> </html>

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.