Devbuddy
Devbuddy

Reputation: 231

scrollToTop is not working on jQuery(document).on('ready', function() {

I'm trying to load my scrolltoTop() function on dom ready, but the event is not firing. Can you please someone help me?

My code is here:

<button class="scroll-top">
<i class="fa fa-angle-up" aria-hidden="true"></i>
</button>

:

"use strict";
function scrollToTop () {
  if ($('.scroll-top').length) {
    $(window).on('scroll', function (){
      if ($(this).scrollTop() > 200) {
        $('.scroll-top').fadeIn();
      }
      else {
        $('.scroll-top').fadeOut();
      }
    });
    $('.scroll-top').on('click', function() {
      $('html, body').animate({scrollTop : 0},1500);
      return false;
    });
  }
}

Here is my DOM ready function:

jQuery(document).on('ready', function() {
  (function ($) {
    scrollToTop ();
  })(jQuery);
});

Using Jquery version: jquery-3.4.1.min.js

Upvotes: 1

Views: 1301

Answers (3)

random
random

Reputation: 7901

use $(document).ready(function() {}

"use strict";

function scrollToTop() {
  console.log('Calling');
  if ($('.scroll-top').length) {
    $(window).on('scroll', function() {
      console.log($(this).scrollTop());
      if ($(this).scrollTop() > 200) {

        $('.scroll-top').fadeIn();
      } else {
        $('.scroll-top').fadeOut();
      }
    });
    $('.scroll-top').on('click', function() {
      $('html, body').animate({
        scrollTop: 0
      }, 1500);
      return false;
    });
  }
}


$(document).ready(function() {
  scrollToTop();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="scroll-top">
   <i class="fa fa-angle-up" aria-hidden="true"></i>
</button>

Upvotes: 1

hellheim
hellheim

Reputation: 71

From jquery documentation , from version 3.0

$( document ).ready(function() {
  // Handler for .ready() called.
});

was replaced with

$(function() {
   // Handler for .ready() called.
});

Maybe try:

$(function() {
   window.scrollTo(0,0);
});

Upvotes: 1

Devsi Odedra
Devsi Odedra

Reputation: 5322

See this demo. when you run script it will scroll to top

jQuery(document).on('ready', function() {

  $(window).scrollTop(0);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="border:1px solid black;width:100px;height:150px;overflow:auto">
This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text.</div><br>

Upvotes: 1

Related Questions