简体   繁体   中英

jquery scrolltop function on click of a button

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>

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.

.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;

   });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM