9

I want to scroll to a specific div on the rendered template. I know I can add an anchor like #something, but I'm rendering the template, I can't change the url. How can I do this?

<div id="something">...</div>
def search():
    ...
    return render_template('search.html')  # should scroll to #something
0

1 Answer 1

14

You can't do anything on the response from the server, but you can add a small JavaScript snippet on the rendered template that will scroll the page to where you want. See Element.scrollIntoView or location.hash.

# pass scroll if you want to scroll somewhere
return render_template('search.html', scroll='something')
<div id="something">
{% if scroll %}
<script>
    document.getElementById('{{ scroll }}').scrollIntoView();
    // or
    document.location.hash = '#' + '{{ scroll }}';
</script>
{% endif %}

See How to scroll HTML page to given anchor? for more information.

If you're redirecting, so you can control the URL, see Link to a specific location in a Flask template.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.