2

I can not figure out why JavaScript is running before the page is loaded. The specific thing I'm waiting on is some images so that I can get their height.

The JavaScript is loaded via hook_preprocess_page(): drupal_add_js(path_to_theme(). '/js/smooth-accordion.js');.

Thanks for any help!

(function ($) {

Drupal.behaviors.listen_to_open = function(item) {
    // item height
    var bodyHeight = item.find('.accordion-body-inner').height();
    var imgHeight = item.find('.multi-image-wrapper li:first img');
    var targetHeight = bodyHeight > imgHeight ? bodyHeight : imgHeight;
    console.log(imgHeight.height());
    item.find('.product-showcase-open').click(
        function(){
            item.find('.multi-image-wrapper').animate({
                height: targetHeight + "px",
            })
            event.preventDefault();
        }
    )
}

Drupal.behaviors.smoothAccordion = {
    attach: function (context, settings) {
                    alert('doh'); // alerts before any text or images appear on page
        var $items = $('.accordion-item-wrapper');
        $items.each(
            function() {
                Drupal.behaviors.listen_to_open($(this));
            }
        )
    }
}
}(jQuery));
  • 1
    @MPDs answer is correct, behaviors execute to soon for what you want to do. However, you may want to consider specifying image dimensions ahead of loading anyway, as that's best practice, and would in some cases solve your problem. (Depending on what you intend to do with the images once you have their dimensions) – Letharion Jun 24 '13 at 21:19
  • 2
    @Letharion It's a debatable topic, but some responsive image techniques advocate not using width/height attributes. I also seem to recall a few early versions or Drupal 7 where the standard theme_image() didn't include them. But, yeah, adding them is usually best unless you have a good reason not to. – mpdonadio Jun 25 '13 at 15:30
  • As @MPD said, because of responsive design, I need the displayed height of the image, rather than it's native height. Thanks to you both! – Chris Rockwell Jun 25 '13 at 16:06
4

Drupal attach behaviors get called from a jQuery ready() callback upon initial page load (it is a little more complicated than that, though). This means that the DOM is ready, but replaced elements may not be done loading. Images are considered replaced elements, so your have a loading bug.

I get around these by using something like imageloaded, or manually attaching via $(window).bind('load', ...);, which will run when the whole page is done loading (including images).

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.