Search code examples
jqueryowl-carouselrefinerycms

Owl Carousel breaks on first coursel


I'm using Owl Carousel in a RefineryCMS project. I have multiple Owl Carousel's on the same page and I switch between these by clicking on a genre. It then shows a number of books relating to that genre. It loads showing all the books, but when I click between one genre and back to the first, the first carousel then modifies the width so that the books run off the side.

Example: When I load it's correct correct carousel

When I click on 'All' which should show the same output I get the following bad carousel

Clicking on 'All' simply hides all the other genres and displays the 'All' genre, here is the code for that;

$(function() {
  $(".genre_link").each(function(){
    $(this).click(function(){
      var genre = this.getAttribute('data-genre'); // Get the genre we are talking about
      $(".backlists").hide(0, function(){          // First hide all
        $("#" + genre).show();  // Show the one genre after all have been hidden.
      });
    })
  })
})

Here is the code I run on loading.

$(".owl-carousel").owlCarousel(
  {
    items: 5,
    itemsDesktop : [500,3],
    itemsDesktopSmall : [400,3]
  }
);

Here is the Carousel

<div id="genres">

    <div class="form-style-2-heading"></div>

    <!-- Genre links -->
    <% @all_genres.each do |genre| %>
        <%= link_to genre[:name], "#/#{genre[:name]}", class: "genre_link", data: {genre: genre[:name]} %>
    <% end %>

    <!-- Books per genre -->
    <% @all_genres.each do |genre| %>
        <div id="<%= genre[:name] %>" class="backlists">
            <div class="owl-carousel">
                <% genre[:backlists].each do |backlist| %>
                    <div>
                        <li>
                            <%= image_fu(backlist.picture, "120x160#") %>
                            <br />
                            <div class="product_title">
                                <%=raw backlist.title %>
                            </div>
                            <div class="product_author">
                                <%=raw backlist.author %>
                            </div>
                        </li>
                    </div>
                <% end %>
            </div>
        </div>
    <% end %>

</div>

If I put a blank as the first in the array then it fixes the problem. This is a very hacky solution and then causes other problems with having a blank in the menu.


Solution

  • Just found my answer which was not in the question

    I was setting the first of the backlists ('All') to inline, when I should of been using block

    from

    $(".backlists").first().css("display", "inline")
    

    to

    $(".backlists").first().css("display", "block")