Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 141891

how to use history.pushState to return to the first page of my site

$
0
0

I work on the skeleton of a onePage site, based on the use of hashtags (the site is a presentation on usb key)

The idea is to be able to use the back and forth buttons in the browser history (history prev / next)

the problem:
I have a button to return to the main page (Zorro page) but I can't trigger:
1 = a rewrite of the url (which will not trigger a reload of the site)
2 = trigger an evt = hashchange, so that it can place the content of the zorro page

I read the doc 10 times on history.pushState but I lose my Latin there

here is my test code:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Zorro</title>
  <style>
    div { border: 1px solid grey; padding: 1em; margin: 1em; width: 6em; height: 1.4em;}
    button { visibility: hidden;  }
    .visu  { visibility: visible; }
  </style>
</head>
<body>
  menu : <a href="#aaa">goto A</a> <a href="#bbb">goto B</a> <a href="#ccc">goto C</a>

  <div id="content">page Zorro</div>

  <button id="bt-return">return to page Zorro</button>

  <script>
  const ihmContent = document.getElementById('content')
    ,   btReturn   = document.getElementById('bt-return')
    ,   docTitle   = document.title
    ;
  window.onload =_=>
    {
    goto(window.location.hash)
    } 
  window.onhashchange=e=>
    {
    e.preventDefault();
    goto(window.location.hash)
    } 
  function goto(x_hash) // change page (basic sample code)
    {
    switch (x_hash)
      {
      case '#aaa': ihmContent.textContent = 'page A';    document.title = '-A-';    break;
      case '#bbb': ihmContent.textContent = 'page B';    document.title = '-B-';    break;
      case '#ccc': ihmContent.textContent = 'page C';    document.title = '-C-';    break;
      default:     ihmContent.textContent = 'page Zorro'; document.title = docTitle; break;
      }
    btReturn.className = (ihmContent.textContent === 'page Zorro') ? '':'visu';
    }
  btReturn.onclick=_=>
    {
    history.pushState(window.location.pathname, docTitle) // do nothing  !
    } 
  </script>
</body>
</html> 

Viewing all articles
Browse latest Browse all 141891

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>