Improvements to the experience of filtering posts by tags

Hello! I’ve been following the video to filter posts by tags:

It’s pretty useful, and I have it working. However, the experience that I got working could be improved. There are a couple of things I didn’t manage to make work:

1) How the link to category doesn’t go back to the top of the page? Ideally, I’d rather prefer to keep the same scroll position.

2) And the other thing, is that there’s an “All categories” item. For the rest of categories, there’s an “active” class applied when they are selected, but I couldn’t make this to do the same.

There’s a code example here that closely resembles the example:

        <nav>
            <a href="<?= $page->url()?>">All</a>
            <?php foreach ($filters as $filter): ?>
                <a href="<?= $page->url() ?>?filter=<?= $filter ?>" class="<?= $filterBy === $filter ? 'active' : '' ?>"><?= $filter ?></a>
            <?php endforeach ?>
        </nav>

Perhaps anyone has already gone through this and solved it?

Add the active state on the condition that the filter is not set/empty.

Something like

<?php $filterBy = get('filter') ?>
    <nav class="filter">
      <a href="<?= $page->url() ?>" class="<?= $filterBy === '' ? 'active' : '' ?>>All</a>
      <?php foreach ($filters as $filter): ?>
      <a href="<?= $page->url() ?>?filter=<?= $filter ?>" class="<?= $filterBy === $filter ? 'active' : '' ?>><?= $filter ?></a>
      <?php endforeach ?>
    </nav>

Thanks! I will try. Since I don’t have much idea, I used a similar format than the other one, that seems to work, too:

<a href="<?= $page->url()?>" class="<?= $posts === $unfiltered ? 'active' : '' ?>">All</a>

But I’m not really sure in terms of good practices and such. I just based this on the other one. But will try yours as well.

What I have now missing, is this weird scroll behaviour when I click on each filter. That the scrolls resets to the topo. But I’m unsure if this is avoidable.

Well, with the anker tags, you are reloading the page when filtering. To keep the scroll position, you probably need a JS based solution, so you can listen to scroll position. That’s not really Kirby related, but frontend stuff.

Yes, I understand. It makes sense. Thanks for the suggestion.