DEV Community

Cover image for Simulate single page app using CSS selector (:target)
mohamed farid
mohamed farid

Posted on • Updated on

Simulate single page app using CSS selector (:target)

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;
 }

Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

if the URL does not have hash push to the home page

if (window.location.hash === "") {
  window.location.hash = "#home";
}
Enter fullscreen mode Exit fullscreen mode

to listen to the page change

window.addEventListener("hashchange", (e) => {
});
Enter fullscreen mode Exit fullscreen mode

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);
  }
});
Enter fullscreen mode Exit fullscreen mode

you can check the full example here

Any feedback is appreciated 🤝

Top comments (7)

Collapse
 
dennisfrijlink profile image
Dennis Frijlink

I don't think this is the best solution for a SPA but I like the idea and the simplicity!

 
matjones profile image
Mat Jones

Yeah it also means you have to send fully hydrated renders for every page in the entire app for it to work properly

Collapse
 
darcdev profile image
Diego Andres Rojas

Thanks bro, that method give me other ideas. 😁

Collapse
 
_faridjunior profile image
mohamed farid

you're welcome ♥

Collapse
 
_faridjunior profile image
mohamed farid • Edited

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