LetsFlow
LetsFlow

Reputation: 31

How to forward using Javascript without changing page URL?

I have a home page, and I want to navigate to other pages, say blog or gallery, but without the URL in the address bar to change. I know it's possible on server side, but how to do in Javascript?

Here is my HTML/JS code:

//HTML
<ul>
  <li><a onclick="openPage('contact.html')">Contact Us</a></li>
  <li><a onclick="openPage('blog.html')">Blog</a></li>
  <li><a onclick="openPage('gallery.html')">Gallery</a></li>
</ul>

//Javascript
function openPage(url){
     //   All these will forward but will change the URL
     //window.open(url);
     //window.location.href=url;
     //self.location=url;
     //window.location.replace(url);
}

Initially, the URL will be http://something.com/mainpage.html

And it should stay the same even when navigating to any page.

This is a very simple example of what I have. So, is it possible on client side without server? If not, then what would be the simplest way to do it on server side? Assuming I'm using Java/JSF.

Upvotes: 3

Views: 1397

Answers (2)

anishsane
anishsane

Reputation: 20980

I will give you a hint. You can then write the code on your own.

Using ajax, fetch the entire page you want to open. (I assume that they are on the same server.)

Then parse the html.responsetext & find the body.innerHTML of the fetched page.
then use document.body.innerHTML=fetched_body_innerHTML;
Change the document.title also in similar manner.

I am assuming that both pages will have same CSS (for consistency in looks), and quite possibly, same js files loaded.

If you have different set of CSS &/or js files on the 2 pages, you will need to create additional nodes & delete old script/link nodes. (However, the result will not be identical, since old JS was already loaded & body.onload will not be triggered after you change the innerHTML of the body.

Upvotes: 0

Ghostman
Ghostman

Reputation: 6114

You will have to add hash # if you want to prevent page from reloading.

The css-tricks.com has an excellent screencast on that, have a look at:

Best Practices with Dynamic Content

please check this question in stackoverflow changing-the-url-without-reloading-the-page

Upvotes: 2

Related Questions