Automatically scroll to div when Flask returns rendered template
I want to scroll to a specific div on a rendered template. I know I can add an anchor for example #something
, but I am rendering the template, I cannot change the url. How can i do this?
<div id="something">...</div>
def search():
...
return render_template('search.html') # should scroll to #something
+3
source to share
1 answer
You cannot do anything in response from the server, but you can add a small piece of JavaScript to the rendered template that will scroll the page to wherever 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 an HTML page to a given anchor using jQuery or Javascript? for more information.
+5
source to share