Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

brentxscholl's avatar

Scroll to an HTML element when returning a view

I know I can redirect to a route and scroll to an HTML element by doing:

return redirect()->route('route-name', [ '#element'])

How can I do the same thing but when creating a view?

return view('view.name', compact('some-variable')); // scroll to #element

Is this possible?

0 likes
3 replies
Snapey's avatar
Snapey
Best Answer
Level 122

you could redirect to the same route with the anchor added to the route, then prepare the data and return the view?

Alternatively, include a snippet of javascript that scrolls to the correct page or the correct tab. The snippet could be passed the anchor label in the view

1 like
brentxscholl's avatar

Thanks for the reply! I like the passing a variable idea.

Here's what I did:

Controller

    $scroll = true;
    return view('view.name', compact('scroll'));

In the view I added some js

    $(document).ready(function () {
        @if($scroll)
            $('html, body').animate({
                scrollTop: $('#element').offset().top
            }, 'slow');
        @endif
    });
1 like
Gass's avatar

cool solution, thanks for sharing!

Please or to participate in this conversation.