How can I jump to an anchor on the page after my custom module search results are displayed?

I have a search form far down on the page; and when the page refreshes to display results, the results are not in view. I want to automatically jump to the anchor above the search results after they are displayed.

Hi @shannonlynd. You should just be able to add your ID/anchor to you search form’s action address. Then when the page loads the action URL, it’ll append the hash and go to the anchor ID.

<form action="#target">
    <div>
          <input type="text" name="SearchKeyword"  />
          <input type="submit" value="Search" />
    </div>
</form>

Alternatively, if you need more control/options, you could have some condition Liquid that only shows some javascript when the page URL included the search parameter/s.
Then the JS will only fire when a search is done (and the JS scrolls the page to your anchor and anything else you need it to do).

eg:

{% if request.request_url.params.SearchKeyword %}
    <!-- jQuery scroll method -->
    $(document.body).animate({
        'scrollTop':   $('#anchorName2').offset().top
    }, 2000);
{% endif %}

Lots of other page scroll options here for reference:

I tried the form action way - but it’s scrolling the form to the middle of the results each time, not to the anchor.
You can see it on this site that’s under construction - https://leda.treepl.co/doing-business/covid-business
The anchor is at the top of the search box. You can see that the “Top of List” button works and goes where the anchor should have landed.

I’ll give the javascript method a try.

Thanks!!

Here’s what provided the most consistent results:
{% if request.request_url.params.prop_KeyWords %}
document.getElementById(‘form-top’).scrollIntoView({ behavior: ‘smooth’, block: ‘end’, inline: ‘start’ });
{% endif %}

2 Likes