Search code examples
javascriptjqueryowl-carousel-2

Callback on owl carousel AFTER fully drawn on page


Imagine you have a single item carousel that sits at the absolute top of the page. Under that, you have the rest of your content. As the carousel is nested arbitrarily deep in the page, you've set it up to be absolutely positioned. But now you need to know how high the carousel is so you can put a top margin on the rest of the content so it does not overlap. This is what I am doing.

$('#carousel').owlCarousel({
  items: 1,
  onInitialized: adjustStretchHeader,
  onResized: adjustStretchHeader
});

function adjustStretchHeader () {
  setTimeout(function () {
    return $('.page > .container')
      .css('margin-top', $('.page > .stretch-header')
        .height() + 15);
  }, 250);
}

On the initialisation of the carousel and on resize events, I am getting it to get the carousel's height and update the top margin. The problem is that, without having a delay, the initialized event is triggering before the carousel is fully drawn on the page, so the height is unreliable.

With a delay, I'm able to get it properly. But this is obviously a hack, and I cannot guarantee that on slower devices, the carousel will have been drawn in time.

I cannot see any other useful events in the documentation.

Demonstration fiddle


Solution

  • You can use jQuery's get() method to grab the height of the images (even when they're hidden). This is independent of owlCarousel so don't have to wait for it to finish loading!

    var images = $('#carousel img');
    var firstImgHeight = images.get(0).height;
    $('.page > .container').css('margin-top', firstImgHeight + 15);