Created
June 30, 2018 08:31
-
-
Save furenku/290609640a9a3cee502ec53c6535917c to your computer and use it in GitHub Desktop.
history test
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <!DOCTYPE html> | |
| <html lang="en"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
| <meta http-equiv="X-UA-Compatible" content="ie=edge"> | |
| <title>Document</title> | |
| </head> | |
| <body> | |
| <button onclick="back()">back</button> | |
| <main> | |
| <p>primer contenido</p> | |
| </main> | |
| <button onclick="forward()">forward</button> | |
| <button onclick="loadPage('secondpage.html')">segunda página</button> | |
| <button onclick="loadPage('other.html')">otra página</button> | |
| <button onclick="changeUrl()">random url</button> | |
| <script> | |
| var p = document.querySelector('p') | |
| p.textContent = 'carga inicial' | |
| function back() { | |
| history.back() | |
| } | |
| function forward() { | |
| history.forward() | |
| } | |
| function changeUrl() { | |
| console.log("changeurl") | |
| let newValue = Math.round( Math.random()*100 ); | |
| let newHtml = document.createElement('p').innerHTML = `nuevo valor ${newValue}` | |
| history.pushState({content:newHtml},'new state','page-'+newValue+'.html') | |
| setView(newHtml) | |
| // history.pushState({value:Math.round(Math.random()*100)},'new state','?new='+Math.random()) | |
| } | |
| function setView( value ) { | |
| document.getElementsByTagName('main')[0].innerHTML = value | |
| // p.textContent = `página ${value}` | |
| } | |
| function loadPage(url) { | |
| fetch(url) | |
| .then(res=>res.text()) | |
| .then(html=>{ | |
| console.log(html) | |
| let container = document.createElement('div') | |
| container.innerHTML = html | |
| let content = container.getElementsByTagName('main')[0].innerHTML | |
| history.pushState({content:content},'intro','') | |
| setView(content) | |
| }) | |
| } | |
| window.onpopstate = function (e) { | |
| setView(e.state.content) | |
| } | |
| let firstContent = document.getElementsByTagName('main')[0].innerHTML | |
| history.replaceState({content:firstContent},'intro','') | |
| </script> | |
| </body> | |
| </html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment