
I was building a single page web app, and needed the page to refresh with new information without actually reloading the page with jQuery. Here’s how I did it.
The first thing you’ll want to do is set up your HTML, like this:
<body id="body-content">
<div class="main-content">
<!--Left side-->
<div class="left-side">
<img src="images/image 1.png" alt="my-image">
</div>
<!--Right side-->
<div class="right-side">
<div class="logo">
<img src="images/Group 1.png">
</div>
<div class="right-side-content">
<div class="right-side-home">
<div class="heading">
<h1 id="heading">Hello!</h1>
</div>
<div class="bottom-section">
<h3>Click below to get started.</h3>
</div>
</div>
<div id="next">
<a href="#next">Next</a>
</div>
</div>
</div>
</div>
Now, let’s say I wanted to change the <h1>Hello!</h1>
into <h1>Welcome to the app!</h1>
, without reloading the page with jQuery.
You’ll first create a new HTML page, with all the same content as the previous page, but now you’ll change the elements you want to be different. <h1>Hello!</h1> becomes <h1>Welcome to the app!</h1>
You’ll also need to change the id.
Then, to connect the two pages together, you’ll do something like this in jQuery:
$('#next').on('click', function () {
var url = "http://127.0.0.1:5502/first-page.html #newheading";
$('#body-content').load(url)
});
“$(‘#next’)” is my a tag, and I’m telling the browser: When this is clicked, you see this link? Refresh, or load this page with any new content, but keep anything on the page that’s common between the two pages.
For this to work, your body content will need to be wrapped in an ID, not a class.
(Side note: This can also work with using Ajax as well, but I used this load() method for this simple app.)
How this works explained by jQuery.com: “When this method executes, it retrieves the content of ajax/test.html, but then jQuery parses the returned document to find the element with an ID of container. This element, along with its contents, is inserted into the element with an ID of result, and the rest of the retrieved document is discarded.” Link: https://api.jquery.com/load/
This is how you can reload the page without the page refreshing with jQuery. This is also how a simple single page application (or SPA) is built.
In other words, the browser will take the link you gave it, look through what you want to change, change that, and throw away everything else using jQuery.
Hope this help.