3

Currently, in my theme.info file I am including 2 scripts:

scripts[] = js/backstretch.js
scripts[] = js/scripts.js

Backstretch is a jQuery plugin that allows for an expanding background image to cover your entire page.

I am currently using this code to autoload the JS:

(function ($) {

    var bgs=["bg1.jpg", "bg2.jpg"];
    var bgr=Math.floor(bgs.length * Math.random());
    $.backstretch(bgs[bgr], { speed: 1000 });

})(jQuery);

Two issues:

  1. Sometimes it doesn't load the backstretch.js properly which may have something to do with my current OnLoad function in scripts.js. It loads the image but not maximum width/height of the browser initially.
  2. For some reason, it doesn't work past 1 level in the site (although the JS seems to load when I check the site (could it be that the location of images is not relative of the JS file?) e.g.,:

Works: site.com, site.com/page

Doesn't Work: site.com/dir/page, site.com/dir/dir/page

I was wondering in my scripts file what would be the best OnPageLoad (or Preload?) function would be best to use?

Many thanks in advance.

1

1 Answer 1

6

Please read Managing JavaScript in Drupal, specifically the section on Behaviors. You'll need to do something like this:

(function ($) {

  Drupal.behaviors.exampleModule = {
    attach: function(context, settings) {
      var bgs=["bg1.jpg", "bg2.jpg"];
      var bgr=Math.floor(bgs.length * Math.random());
      $.backstretch(bgs[bgr], { speed: 1000 });
    }
  };

})(jQuery);
7
  • Can you expand on the "exampleModule" thing? I just want it to run when the best way when the page loads. Would if be "Drupal.behaviours.OnLoad" ? Thanks for the help so far. May 11, 2011 at 5:22
  • 1
    That' s just a variable name for your code. You can use anything, but must use a module prefix. Behaviours are all executed on load.
    – Berdir
    May 11, 2011 at 6:17
  • Ok I will try it out when I get home, thankyou May 11, 2011 at 7:17
  • Matt, what did you use instead of "exampleModule"
    – user12515
    Jan 6, 2013 at 21:13
  • @Berdir "Behaviours are all executed on load." - not sure what you mean here, but my understanding is that behaviours are executed when the DOM is ready, i.e. the pure JQuery equivalent is running code inside the ready function, as the ready function is executed once the DOM is ready. Feb 5, 2014 at 16:00

Your Answer

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

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