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>
  • If you do it like this, the link won't work if the user has Javascript disabled. – Patrick Kenny Oct 6 '17 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? – usernameabc Oct 6 '17 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. – Patrick Kenny Oct 6 '17 at 16:23
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.

| improve this answer | |
  • yes for some reason the portion you added has worked for me. I have done this on multiple drupal behaviors now. – usernameabc Oct 13 '17 at 17:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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