0

I am newer to JavaScript and I am working on a website where I want to be able to switch the URL when I click on certain elements of the site without reloading the page.

I want it to work like http://www.itemcycle.com when you click on the link to sell your iPad or iPhone and then select your model. It shows different boxes, and when you click on them, it changes the URL but I know it's not loading a new page because it doesn't scroll me back to the top.

Thanks in advance for your help!

  • 1
    Possible duplicate of [Modify the URL without reloading the page](http://stackoverflow.com/questions/824349/modify-the-url-without-reloading-the-page) – WirelessKiwi May 12 '16 at 08:32

4 Answers4

1

what you are seeing is a single page application

A single-page application (SPA), also known as single-page interface (SPI), is a web application or web site that fits on a single web page with the goal of providing a more fluid user experience akin to a desktop application.

It will be achieved by using certain JS frameworks. AngularJS is the popular one.

Wild Widow
  • 2,359
  • 3
  • 22
  • 34
0

Try this:

window.location.href="/yourUrl";
Husni Salax
  • 1,968
  • 1
  • 19
  • 29
0

HTML5 introduced the history.pushState() which allows you to add and modify history entries.

window.history.pushState('page1', 'Title', '/page1.php');

This might worth looking.

Naqash Malik
  • 1,707
  • 1
  • 12
  • 14
0

There's 2 main ways to redirect a user, each with it's tradeoffs:

  1. You can redirect a user to a new page by changing the value of window.location.href. So for instance window.location.href='https://example.com'; will redirect a user to https://example.com. Note this will do a hard page reload, so the page will actually reload.

  2. To change the url path without redirecting the user to a new page you can do use history.pushState. Doing something like:

    history.pushState({}, "page 2", "/page2");

    will change the url from https://example.com to https://example.com/page2 and the scroll position won't change. You can then listen to changes from history.pushState and update the page accordingly giving you effect you're looking for. Note you cannot change the domain (i.e. you can't go from https://example1.com to https://example2.com), but on the plus side the page will not actually be reloaded.

As others have pointed out there are various frameworks which allow you to do this type of thing, but those frameworks are making use of the techniques I've described above.

winhowes
  • 7,845
  • 5
  • 28
  • 39