0

I used scrolltop function to scroll to top on click of a button but it is not working?

** jquery ******

jQuery('.scroll').click(function () 
{
  jQuery("html, body").animate({ scrollTop: '#fields2' }, 'slow');

    return false;

   });

***** html code *****

  <div id="fields2"> 
      ..............
 ...............

       <input class="send_btn scroll" type="button" value="back"/>
      </div>
1
  • try scrollTop: $('#fields2').offset().top Commented Apr 3, 2014 at 13:06

2 Answers 2

1

Just ask yourself : scrollTop is a property that indicate the distance from the top of the document, in pixels.

There, you ask jQuery to animate the scrollTop to "#fields2", which is a string.

So, first, I guess you try to retrieve the distance of element #fields2 from top ?

This way : $('#fields2').offset().top

jQuery('.scroll, .send_btn').click(function (e) 
{
 e.preventDefault(); 
 var dest = $('#fields2').offset().top;
 jQuery("html, body").animate({ scrollTop:  dest }, 'slow');

 // If you need to submit a form, with an input like : <input type="submit" class="send_btn" value="Submit"/>
 if(jQuery(this).hasClass('send_btn')) { // check if you've clicked on .send_btn
    $(this).parents('#myForm').submit(); // submit the form.
 }


});

Note : I replaced return false by e.preventDefault(). return false is not standard way to stop fire events.

Edit : As e.preventDefault(); stops the events on the element, you must manually submit the form with jQuery, as seen in the code above.

Sign up to request clarification or add additional context in comments.

3 Comments

It worked fine so thank you everybody. There is also a submit button <input class="send_btn" type="submit" value="Register"/> which should also submit the form and scroll to #fields2. If i give scroll class for the button the submit functionality is not working.
Edited the answer with a solution to your new problem.
@mujtaba: If this answer resolved your issue, please don't forget to mark your question it as answered by checking the checkmark before the answer.
0

.offset() returns the coordinates of an element relative to the document, and top param will give you the element's distance in pixels along the y-axis:

jQuery('.scroll').click(function () 
{
  jQuery("html, body").animate({ scrollTop:  $('#fields2').offset().top }, 'slow');

    return false;

   });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.