Monday, June 25, 2018

phpMyPassion

How to Create a Scroll To Top With Some Delay Using JavaScript ?

Here I am sharing the code for scrolling a page from bottom to top with some delay. You can also use that to reach or show first error element box in your specified form.

Javascript scroll to top with some delay  || PhpMyPassion

 Show First Scrolled Error Element Box on Submit :-

you can use below jQuery code to scroll on the first error element box on submit -

$('html, body').animate({
                scrollTop: $(validator.errorList[0].element).offset().top-300            }, 2000);

Above code will work for the form group on submit. for an example below -

$("#submit").on('click', function () {

    var validator = $("#form").validate({
        rules: {
           name: {
                required: true,
                maxlength: 50            },
        },
        messages: {
            nam: {
                required: "This field is required.",
                maxlength: "name must be less than 50 character.",
            }
        },
        highlight: function (element) {
            $(element).closest('.form-group').removeClass('success').addClass('has-error control-label');
            /*scroll to first error element box */
            $('html, body').animate({
                scrollTop: $(validator.errorList[0].element).offset().top-300            }, 2000);
        },
        success: function (element) {
            element.addClass('valid').closest('.form-group').removeClass('has-error control-label').addClass('success');
        }

    });
}

Above code will scroll you back to your first error input box with animation.

Animated scroll back to top for a specified element ID :-

If you want to scroll back to  a specified element Id on some event then you can use below code -

$('html, body').animate({
    scrollTop: $("#elementId").offset().top-300}, 2000);


.scrollTop() jQuery Function :-

You can also use .scrollTop() function to scroll bottom to top on a page.

Note:- .scrollTop() function does not accept any arguments.

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>My wep page scrollTop demo with jquery</title>
  <style>
  div {
    margin: 10px;
    padding: 5px;
    border: 2px solid #666;
  }
  </style>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
 
<div>Dashboard</div><div></div>
 
<script>
var div = $( "div:first" );
$( "div:last" ).text( "scrollTop:" + div.scrollTop() );
</script>
 
</body>
</html>



About Author -

Hi, I am Anil.

Welcome to my eponymous blog! I am passionate about web programming. Here you will find a huge information on web development, web design, PHP, Python, Digital Marketing and Latest technology.

Subscribe to this Blog via Email :

Note: Only a member of this blog may post a comment.