Hash Router (Single Page)
JavaScript
Hard
4 views
Problem Description
You have a container #view and multiple templates , etc. Use location.hash (like #home). On hash change, render matching template into #view. Default to home.
Output Format
No output (DOM change).
Constraints
Assume templates exist with ids matching route names and #view exists.
Official Solution
const view=document.getElementById('view');const render=()=>{let route=(location.hash||'#home').slice(1).trim()||'home';const tpl=document.getElementById(route);if(!(tpl instanceof HTMLTemplateElement)){route='home';}const t=(document.getElementById(route));view.innerHTML='';if(t instanceof HTMLTemplateElement)view.appendChild(t.content.cloneNode(true));};window.addEventListener('hashchange',render);render();
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!