Shuffle the order of my posts

There was an interesting question posted in the forums recently by a user named Gayathri, where he was hoping to shuffle the order in which his posts appear. This is achievable, so far as I can see, one of two ways - custom markup (server-side shuffling) or JS (client-side shuffling).

However, because the output of any given server-side render might be cached, for the next viewer, the shuffled output order would persist, and each viewer would only see the same (random) order.

JS Shuffling

We can shuffle the content once the page has loaded on the client, which would produce a different result for each view. Note that this does have the downside of potentially causing content jankyness, but should execute fast enough not to be noticed by the reader.

We shuffle the order of posts by removing and re-inserting sibling posts in a random postion. See the MDN general sibling selector documentation for more detail.

var posts = document.querySelectorAll(
  '.post-outer ~ .post-outer,'
  + ' .post-outer-container ~ .post-outer-container,'
  + ' .date-outer ~ .date-outer');
posts.forEach(p => {
  var parent = p.parentElement;
  p.remove();
  var position = Math.floor(Math.random() * parent.children.length - 1);
  parent.insertBefore(p, parent.children[position]);
});

You can add this JS to your blog in a custom HTML gadget, by clicking the button below.



Happy shuffling!

Comments

  1. How You make your blog amp... https://so-how-do-i.blogspot.in/2017/05/offset-html-anchor-to-adjust-for-sticky.html?amp=1

    ReplyDelete

Post a Comment

Popular posts from this blog

Filter out certain labels from my Blog Homepage

Change the landing page of my blog

Get Facebook to show feature image for your Blog's Homepage