0

I have added the following Drupal behaviors below to my main.js file which is already included in my theme and renders on the page with the correct main.js file. The purpose of this behavior is to scroll the user to the top of the page and it is not working. I cannot even get it to log an alert('clicked'). Need help figure out what i am missing.

main.js

Drupal.behaviors.scrollToTop = {
  attach: function (context, setting) {
    $('#back-to-top', context).on('click', function(){
        alert('clicked'); //does not work
        $('body,html').animate({scrollTop : 0}, 500); //does not work
    });
  }
};

html

<body>
  <!-- assume this is at the bottom and there is more in the body -->
  <a id="back-to-top" href="javascript:void(0)";><div>div is used to insert up arrow</div></a>
</body>
3
  • If you do it like this, the link won't work if the user has Javascript disabled. Commented Oct 6, 2017 at 3:06
  • @PatrickKenny are you refering to the javascript:void(0) portion? i am trying to understand what portion of the code will make it not work when Javascript is disabled? I would love to see an example of how it would work even with javascript turned off? Commented Oct 6, 2017 at 15:46
  • You can do this without any javascript by making an inner document link to an element with an id at the top of the page. For example, in bootstrap theme, <a href="#navbar">Back to top</a> will work on any page with a navbar. Commented Oct 6, 2017 at 16:23

1 Answer 1

1

Try wrapping it:

(function ($) {
    Drupal.behaviors.scrollToTop = {
      attach: function (context, setting) {
        $('#back-to-top', context).on('click', function(){
            $('body,html').animate({scrollTop : 0}, 500);
        });
      }
    };
}(jQuery));

Had the same issue, AFAIK the wrapper is necessary to actually fire the behavior.

1
  • yes for some reason the portion you added has worked for me. I have done this on multiple drupal behaviors now. Commented Oct 13, 2017 at 17:48

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.