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

Shiva's avatar

How to get page to scroll to a section when a button is clicked

I'm trying to get my page to scroll to a specific point on my page if there is errors after submitting a form. My page scrolls down but then jumps up to a different section. I'm using Laravel 4.

my contact.blade.php

{{ Form:: open(array('url' => 'contact_request#contact')) }}
          {{ Form:: text('name', '', array("class" => "form-control", 'placeholder' => 'Name')) }}
          {{ Form:: email('email', '', array("class" => "form-control", 'placeholder' => 'Email')) }}
          {{ Form:: text('subject', '', array("class" => "form-control", 'placeholder' => 'Subject')) }}
          {{ Form:: textarea ('message', '', array("class" => "form-control", 'placeholder' => 'Your Message')) }}
          {{ Form::submit('SEND', array('class' => 'submit_btn')) }}
        {{ Form:: close() }}
0 likes
29 replies
mstnorris's avatar
  1. Show errors and give containing div an id and an <a name ...
  2. Use JavaScript or jQuery to look for said id
  3. Use JavaScript or jQuery to scroll to the position of the a tag.
willvincent's avatar

You shouldn't need an a tag, just the id to scroll to, and/or set that id as a fragment on the url..

ie: example.com/some/path#id-goes-here

Shiva's avatar

@willvincent - I've done that

{{ Form:: open(array('url' => 'contact_request#contact')) }}

and what happens is that it first goes there and then jumps up

Shiva's avatar

Here is a link to the demo site I'm working on http://clients.webkrunch.co.za/webkrunch/ if you click on contact you will scroll down to the contact form. If you just click send the page will refresh and you will be taken to a section just before the portfolio page.

willvincent's avatar

When I click the send button it jumps back to the form with error messages for me.. maybe this is a browser issue?

Shiva's avatar

@willvincent - thanks I didn't think of trying on a different browser. Can you please tell me what browser you used. I'm using the firefox 40.0.3

willvincent's avatar

I'm in Chrome 45.0.2454.85 (64-bit), on OSX 10.10.5

But if it's not working in all browsers, you will probably need some javascript to address it. Something along these lines ought to work (assuming you have jQuery installed):

(function ($) {
  $(document).ready(function() {
    if (typeof window.location.hash !== 'undefined') {
      $("html, body").animate({ scrollTop: $('#' + window.location.hash).offset().top }, 1000);
    }
  });
})(jQuery);
Shiva's avatar

@willvincent - that still doesn't work I get this error in my console

Error: Syntax error, unrecognized expression: ##contact
sid405's avatar

@Shiva

i do this


$('.item').click(function() {

    var url = $(this).data('url'); // THE ID OR THE ELEMENT YOU ARE TRYING TO SCROLL TO

    //make up for the navbar height     
    var navbar_height = parseInt($('.navbar').css('height').replace('px', ''));

    // the 25 is just a bit more margin
    animate_scroll(url, navbar_height, 25);

});

//element - item you trying to go to
//variable - other height to account for - in my case navbar - feel free to remove it or set to 0 in your call
//offset - other offsetting for margin
function animate_scroll (element, variable, offset) {
    $('html, body').stop().animate({
        scrollTop: $(element).offset().top - variable - offset
    }, 600);
}

And it works just fine. I been using it for a long time. No need for plugins.

Hope it helps.

Best,

sid

Shiva's avatar

@sid405 - I don't know if I'm doing anything wrong, but it doesn't work. This is what I've done

$('.submit_btn').click(function() {

    var url = $(this).data('#contact'); // THE ID OR THE ELEMENT YOU ARE TRYING TO SCROLL TO

    //make up for the navbar height     
    var navbar_height = parseInt($('.navbar').css('height').replace('px', ''));

    // the 25 is just a bit more margin
    animate_scroll(url, navbar_height, 25);

    });

//element - item you trying to go to
    //variable - other height to account for - in my case navbar - feel free to remove it or set to 0 in your call
    //offset - other offsetting for margin
    function animate_scroll (element, variable, offset) {
        $('html, body').stop().animate({
            scrollTop: $(element).offset().top - variable - offset
        }, 600);
    }

and I changed the url in my form from

contact_request#contact

to

contact_request

I also got this error when I submitted my form

TypeError: $(...).offset(...) is undefined
    

scrollTop: $(element).offset().top - variable - offset

with the arrow pointing to the $

sid405's avatar

@Shiva What is the element you're trying to scroll to when the button is clicked?

sid405's avatar

@Shiva Yea but is it a link, a div, or some other element

can i see the html of that element?

Shiva's avatar

@sid405 - Sure.

<section id="contact">
  <div class="container">
    <div class="row">
      <div class="col-lg-12 col-md-12 col-sm-12">
        @foreach($test_menu as $menu)
          @foreach($menu->content as $content)
            @if($content->title == 'Contact Us')
              <div class="heading">
                <h2 class="wow fadeInLeftBig">{{ $content->title }}</h2>
                <p>{{ $content->content }}</p>
              </div>
            @endif()
          @endforeach()
        @endforeach()
      </div>
    </div>
    <div class="row">
      <div class="contact_content">
        <div class="col-lg-5 col-md-5 col-sm-5 col-md-offset-3">
          <div class="contact_form">
            <div id="form-messages1"></div>
            @foreach($errors->all(':message') as $message)
              <div id="form-messages" class="alert alert-danger" role="alert">
                {{ $message }}
              </div>
            @endforeach()

            @if(Session::get('success') == true)
              <div class="alert alert-success">
              {{ Session::get('success') }}
            </div>
            @endif()
            
            {{ Form:: open(array('url' => 'contact_request', 'id' => 'contact_form')) }}
            <meta id="token" name="token" content="{{ csrf_token() }}">
              {{ Form:: text('name', '', array("class" => "form-control", 'placeholder' => 'Name', 'id' => 'name')) }}
              {{ Form:: email('email', '', array("class" => "form-control", 'placeholder' => 'Email', 'id' => 'email')) }}
              {{ Form:: text('subject', '', array("class" => "form-control", 'placeholder' => 'Subject', 'id' => 'subject')) }}
              {{ Form:: textarea ('message', '', array("class" => "form-control", 'placeholder' => 'Your Message', 'id' => 'your_message')) }}
              {{ Form::submit('SEND', array('class' => 'submit_btn', 'id' => 'submit_id')) }}
            {{ Form:: close() }}
          </div>
        </div>
      </div>
    </div>
  </div>
</section>
sid405's avatar

@Shiva Try this then

$('.submit_btn').click(function() {

    var element_to_scroll_to = $('#contact'); // THE ID OR THE ELEMENT YOU ARE TRYING TO SCROLL TO

    //make up for the navbar height     
    var navbar_height = parseInt($('.navbar').css('height').replace('px', ''));

    // the 25 is just a bit more margin
    animate_scroll(element_to_scroll_to, navbar_height, 25);

    });

//element - item you trying to go to
    //variable - other height to account for - in my case navbar - feel free to remove it or set to 0 in your call
    //offset - other offsetting for margin
    function animate_scroll (element, variable, offset) {
        $('html, body').stop().animate({
            scrollTop: $(element).offset().top - variable - offset
        }, 600);
    }
sid405's avatar

@Shiva i click on the navigation items and the scroll is fine.

the problem you have that the button you click is also submitting the form.

  • 1 . it scrolls
    1. submits the form and reloads the page.

Why do you want a form submit button to scroll the page?

Shiva's avatar

@sid405 - so that people can then see if there were any errors or if it was sent successfully

sid405's avatar

@Shiva If is the case, so the page is submitted and reloaded then the scroll does not make sense.

  1. You click the button
  2. Page scrolls
  3. Form submits
  4. Page reloads
  5. How is the scroll supposed to know where to be after you reloaded the page?

2 options.

  1. Make the form post to http://clients.webkrunch.co.za/webkrunch/contact_request#contact
    • add some more margin to include the header so you end up at the beginning of it.
    • you can't use the scroll
  2. Make it an AJAX form
    • on click perform the request
    • when the response arrives scroll to top

I hope you see the logical flaw in the logic you are trying to implement

best.

sid.

sid405's avatar

Or maybe maybe maybe, which has nothing to do with the click of the button (which is what you asked in the subject of the thread), you could

$(document).ready(function () {
    if(window.location.contains("#")) // This doesn't work, any suggestions?
    {
        var pieces = window.location.href.split(/[\s_]+/);
        var section = pieces[pieces.length-1];
    var element_to_scroll_to = $('#' + section);
    var navbar_height = parseInt($('.navbar').css('height').replace('px', ''));
    animate_scroll(element_to_scroll_to, navbar_height, 25);

    }
});

    function animate_scroll (element, variable, offset) {
        $('html, body').stop().animate({
            scrollTop: $(element).offset().top - variable - offset
        }, 600);
    }

Shiva's avatar

@sid405 - I get this error

TypeError: window.location.contains is not a function
    

if(window.location.contains("#")) // This doesn't work, any suggestions?

with the arrow pointing to window

sid405's avatar

@Shiva


$(document).ready(function () {
    if(window.location.href.indexOf("#") >= 0))
    {
        var pieces = window.location.href.split(/[\s_]+/);
        var section = pieces[pieces.length-1];
    var element_to_scroll_to = $('#' + section);
    var navbar_height = parseInt($('.navbar').css('height').replace('px', ''));
    animate_scroll(element_to_scroll_to, navbar_height, 25);

    }
});
Shiva's avatar

@sid405 - I've tried that and it jumps up before portfolio and I get this error

TypeError: $(...).offset(...) is undefined
    

scrollTop: $(element).offset().top - variable - offset

with the arrow pointing to the $

sid405's avatar

@Shiva Dude i can't keep suggesting the code blindly. I already explained the logic and the flaw and i must've give you about 10 code examples.

You can play with it and get it done.

Best of luck

Please or to participate in this conversation.