0

I have a very simple one-page website with four tabs. Clicking on a tab will show one div with content and hide all three other divs and their respective content. I also change the URL with javascript window.history.pushState, so that I go from http://www.example.com to http://www.example.com/Tab2Title.

Obviously the page http://www.example.com/Tab2Title does not exist, so I get a 404 error when I refresh the page after having changed the URL. I then realized that people might want to copy the URL to send it, save it or whatever. Is there a way to load the page with the content of tab2 based on the URL? So that when people load the URL I can display the right content and not a 404 page.

2 Answers 2

1

Yes, there is a way. You can configure your web server to redirect all of the tab URLs to the same page. For example, make it so visiting http://www.example.com/Tab2Title keeps the URL as it is, but shows the same content that would be shown at http://www.example.com/.

The exact code to do this redirecting depends on what web server you are using. For example, it’s different if you have a static website with Apache, or a PHP site, or a Ruby on Rails site.

On the JavaScript side, you should add a “DOM ready” event handler to that single page. The code in that handler should look at the value of window.location, extract the part of the URL that changes for each tab, and show the tab that corresponds to it.


If you are willing to change your existing URLs, there is an easier-to-implement solution. Instead of linking to http://www.example.com/Tab2Title, link to http://www.example.com/#Tab2Title. In a URL, a part like #Tab2Title is called a fragment identifier, and means a link to one section of the page before the #, which is loaded all at once. All web servers should by default treat visiting http://www.example.com/#Tab2Title the same as visiting http://www.example.com/, except when the page loads, the browser will look for an element with id="Tab2Title" and scroll to it if it exists. You can still use window.location in JavaScript to change the page contents as I mentioned above, even if there is no element with that ID on the page.

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

1 Comment

You're right, it's way better using the fragment identifier. It works perfectly, thanks!
0

use # tag for such cases as webserver passes # to clientside (javascript) to process the hastag content (hence you can pass the link to users of the page)

http://www.example.com#Tab2Title

you can process the tabs just as you were on the client side using javascript

window.history.pushState

using this methodolgy is easier and is just what is meant for

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.