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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With