0

I have this code, but I don't know how to wrap it in Drupal.

 $(document).scroll(function () {
    var y = $(this).scrollTop();
    if (y > 100) {
        $('.bottomMenu').fadeIn();
    } else {
        $('.bottomMenu').fadeOut();
    }

});

I've already activated the .js file and added the detail in .info, I can see it from the firebug that is ok, but from firebug console I can see that I have syntax errors.

From Drupal website I can see an example:

(function ($) { // Here code javascript })(jQuery);

Can someone show me how the code above should look like into Drupal? Thanks.

6

Here you go:

(function($) { 
  Drupal.behaviors.yourCustomName = {
    attach: function (context, settings) {

      $(document, context).scroll(function () {
        var y = $(this).scrollTop();
        if (y > 100) {
          $('.bottomMenu').fadeIn();
        } else {
          $('.bottomMenu').fadeOut();
        }
      });

    }
  };
})(jQuery);

Be sure to read the docs.

  • You should always use jQuery once to avoid re-attaching behavior to the same element. And yes, something behaviors are attached multiple time using the root element (ie. document) as context. See coderwall.com/p/kd-4cg for a bit more information on JavaScript in Drupal 7. – Pierre Buyle Sep 9 '13 at 12:48
  • @PierreBuyle always is a bit strong word here. In this case, only on first page load document should be in context. But good hint anyway :) – Mołot Sep 9 '13 at 13:22
  • There is no guarantee that only the page load will apply the behaviors to a context containing the document element. So you can't assume it will never happen. Unless you are ready to review all JavaScript files from all the added modules. – Pierre Buyle Sep 10 '13 at 15:16

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.