hack the idea of SPA using :target css selector (it is a funny idea more than for actual use ) preview
why target selector, because it is the only selector that can understand the URL.
the target selector refers to the element with the id matches
the URL hash
the idea is to give every page id and hide all pages except the current target page
and you can still navigate between pages without javascript
or refresh the page as normal
to hide all pages except the target page
.page:not(:target) {
display: none;
}
put nav to be fixed in all pages
<nav>
<a href="#home">Home</a>
<a href="#about">About</a>
<a href="#contact">Contact</a>
<a href="#posts">Posts</a>
</nav>
create pages that will be affected
<div class="page home" id="home">Home</div>
<div class="page about" id="about">about</div>
<div class="page posts" id="home">posts</div>
if the URL does not have hash push to the home page
if (window.location.hash === "") {
window.location.hash = "#home";
}
to listen to the page change
window.addEventListener("hashchange", (e) => {
});
as example, if you went to get posts
window.addEventListener("hashchange", (e) => {
if (location.hash === "#posts") {
fetch("https://sitetogetposts/posts")
.then((res) => res.json())
.then(setPosts)
.catch(handleError);
}
});
you can check the full example here
Any feedback is appreciated 🤝
Top comments (7)
I don't think this is the best solution for a SPA but I like the idea and the simplicity!
Yeah it also means you have to send fully hydrated renders for every page in the entire app for it to work properly
Thanks bro, that method give me other ideas. 😁
you're welcome ♥
use hash in the URl to style,
build Demo with a few lines of code.
it is a way and you can use it in the right position