Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically scroll to a div when Flask returns rendered template

Tags:

python

flask

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
like image 715
Su Vr Avatar asked Aug 06 '15 18:08

Su Vr


1 Answers

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.

like image 54
davidism Avatar answered Oct 12 '22 23:10

davidism