Search code examples
carouselonsen-ui

OnsenUI: Carousel does not update on orientation change


I am working with fullscreen OnsenUI carousel. The issue is when I swipe/change carousel item and then change the orientation OR resize the window, it does not look good. This issue is with the official OnsenUI carousel example as well.

enter image description here

This is the code I am following:

<ons-carousel swipeable overscrollable auto-scroll fullscreen initial-index="1" var="carousel">
    <ons-carousel-item style="background-color: gray;">
      <div class="item-label">GRAY</div>
    </ons-carousel-item>
    <ons-carousel-item style="background-color: #085078;">
      <div class="item-label">BLUE</div>
    </ons-carousel-item>
    <ons-carousel-item style="background-color: #373B44;">
      <div class="item-label">DARK</div>
    </ons-carousel-item>
    <ons-carousel-item style="background-color: #D38312;">
      <div class="item-label">ORANGE</div>
    </ons-carousel-item>
    <ons-carousel-cover>
      <div class="cover-label">Swipe left or right</div>
    </ons-carousel-cover>
  </ons-carousel>
</ons-page>

This is the Pen from the OnsenUI site.

NOTE: I am using OnsenUI version 1.3.14


Solution

  • It seems like it behaves this way due to a cached value of the item size. The fix requires some hacks with the internal Onsen carousel behaviour, however the development of Onsen 1 is finished, so doing some hacks like these should be safe. What you need to do on a resize event to fix it is the following:

      var i = carousel._scroll / carousel._currentElementSize;
      delete carousel._currentElementSize;
      carousel.setActiveCarouselItemIndex(i);
    

    Here's a demo with the fix applied.

    If you're using angular then you can just use the var="carousel" attribute and you will be able to use carousel in your controller.

    If you don't like angular then selecting it is a little tricky, but not impossible:

    var carousel = angular.element(document.getElementById('carousel')).data('ons-carousel');
    

    Hope this helped.

    Alternatively you could just switch to Onsen 2, where such problems can be fixed quickly in the framework itself.

    Update:

    This bug is fixed in Onsen 2.