Web APIs(5)
history (2)
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="module" defer src="./main.js"></script>
<style>
body {
margin: 0;
}
nav {
background-color: white;
padding: 10px;
border: 4px solid;
position: fixed;
bottom: 0;
right: 0;
}
nav input {
width: 50px;
}
section {
height: 100vh;
border: 10px solid;
box-sizing: border-box;
}
section.page1 {color: red;}
section.page2 {color: orange;}
section.page3 {color: green;}
</style>
</head>
<body>
<nav>
<a href="#/page1">p1</a> /
<a href="#/page2">p2</a> /
<a href="#/page3">p3</a> /
<input type="text">
</nav>
<div id="app">
<section id="/page1" class="page1">
<h1>page 1</h1>
</section>
<section id="/page2" class="page2">
<h1>page 2</h1>
</section>
<section id="/page3" class="page3">
<h1>page 3</h1>
</section>
</div>
</body>
</html>
const page1 = `
<section class="page1">
<h1>Page 1</h1>
</section>`
const page2 = `
<section class="page2">
<h1>Page 2</h1>
</section>`
const page3 = `
<section class="page3">
<h1>Page 3</h1>
</section>`
const pageNotFound = `
<section>
<h1>404 Page Not Found!</h1>
</section>`
const pages = [
{ path: '#/page1', template: page1},
{ path: '#/page2', template: page2},
{ path: '#/page3', template: page3}
]
const appEl = document.querySelector('#app')
const render = () => {
console.log(history)
const page = pages.find(page => page.path === location.hash)
appEl.innerHTML = page
? page.template
: pageNotFound
}
window.addEventListener('popstate', render)
render()
const pagePush = num => {
history.pushState(`전달할 데이터 - ${num}`, null, `#/page${num}`)
render()
}
const inputEl = document.querySelector('nav input')
inputEl.addEventListener('keydown', event => {
if (event.key === 'Enter') {
pagePush(event.target.value)
}
})