How to add back to top using drupal behaviors? 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

&lt;body&gt;
  &lt;!-- assume this is at the bottom and there is more in the body --&gt;
  &lt;a id="back-to-top" href="javascript:void(0)";&gt;&lt;div&gt;div is used to insert up arrow&lt;/div&gt;&lt;/a&gt;
&lt;/body&gt;
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.