Is it possible to implement a circular/infinite carousel using owl carousel? [closed]

自闭症网瘾萝莉.ら 提交于 2019-12-01 02:27:40

Owl Carousel does have the loop: true configuration setting. But, there's a few problems I don't like:

  1. Owl doesn't goto the first slide when at the end, when dragging (instead of clicking on navigation buttons)
  2. Owl rewinds to the first slide, it doesn't wrap around infinitely. This is a big difference, and not nearly as pleasing as a properly circular / infinitely scrolling carousel.

To that end I've found and recommend using the Slick Carousel instead. Slick has a "Center Mode" which had exactly the functionality I was looking for:

http://kenwheeler.github.io/slick/

No.They said that carousel doesn't support circular slides. Possibly this may help:

rewindNav: true

But this works only with navigation arrows, not with responsive slides =(

Or you may huck it somehow)

I was able to accomplish it using jquery/php/ajax. Here is how I did it:

1) First you need to initially place the first x amount of images on the page which will technically be the first page and then afterwards you'll load via ajax each time you reach the end of the carousel. In the example script I supplied I am getting a list of images from a fictional database table called "images". In my php script, for this particular example, it will return 24 owl-item divs with content. For this example I will loading 24 images at a time on the first page initially and then ajax will attempt to return 24 more each time.

HTML (You will need to add the first items into the carousel div and these items will technically be the first page of items. You could use php to populate the divs/image source for the initial first page. Just use regular divs like I did below because the carousel will add the owl-item class to them once it initializes).

<div class="circle-slider">
    <div>
        <img src="/path/to/image/1" />
    </div>
    <div>
        <img src="/path/to/image/2" />
    </div>
        .... the rest of the images go here, each in their own div ....
        .... for this example I'd load 24 images total ...
</div>

Javascript (This javascript goes on the same page as the HTML above.)

<script type="text/javascript">
        $(document).ready(function() {
            var itemsPerPage = 0; // The number of items per page.
            var page = 2; // Start on page 2 since we initially created page 1 in HTML
            var working = false; //Boolean to keep the trigger from firing while we work
            var lastvalue = 0; //last value of the owl objects item position array
            var carouselDiv = '.circle-slider'; // the div that you will be placing the owl carousel on. See HTML above. MUST BE IN jQuery Notation.

            //Normal Owl Carousel Setup. See their site for more options. My example works with these options. No guarantee if you change them to something else that it will work.
            $(carouselDiv).owlCarousel({
                items : 1,
                itemsDesktop : [1920,2],
                itemsDesktopSmall : [980,2],
                itemsTablet: [768,2],
                itemsTabletSmall: [480,1],
                itemsMobile : [370,1],
                singleItem : false,
                itemsScaleUp : false,
                slideSpeed : 800,
                paginationSpeed : 300,
                rewindSpeed : 250,
                pagination:false,
                autoPlay : false,
                afterMove : function() {
                    // This is where all the magic happens. Once you slide the items around and let go this afterMove callback fires.
                    var owl = $(carouselDiv).data('owlCarousel'); //get the current owl carousel object
                    lastvalue = owl.positionsInArray[owl.positionsInArray.length-1]; //Get the last item position value in the position array

                    if((owl.currentItem == owl.maximumItem) && !working){
                        working = true; //Set working to true so we dont fire more events and load more items until this request is finished working
                        $.ajax({
                            method: "GET",
                            url: "/path/to/php/script/see/script/below",
                            async: false,
                            dataType: "script",
                            data: { page: page, itemWidth: owl.itemWidth }
                        }).done(function( data ) {
                            itemsPerPage = parseInt(cresults.numberOfItems, 10);
                            if( itemsPerPage ){
                                $('.owl-wrapper').width($('.owl-wrapper').width() + (itemsPerPage * owl.itemWidth)); //modify the width of the wrapper div to handle the new items
                                $('.owl-wrapper').append(cresults.html); //append the markup
                                owl.maximumItem = parseInt(owl.maximumItem, 10) + parseInt(itemsPerPage, 10); //modify the max items in the owl object
                                for (var i = 0; i < itemsPerPage; i++) { // add new indexes in the position array for the owl object.
                                    lastvalue = lastvalue-owl.itemWidth
                                    owl.positionsInArray.push(lastvalue);
                                }
                                owl.maximumPixels = owl.maximumPixels - (owl.itemWidth * itemsPerPage); //modify the owl maximum pixels to accomodate new items
                                owl.$owlItems = $(carouselDiv).find(".owl-item");
                                page = page + 1;
                            }
                            working = false;
                        });
                    }
                }
            });
        });
    </script>

PHP SCRIPT (Create a php file and this should be the page that is used in the ajax url in the JavaScript i.e. $.ajax({method: "GET",url: "/path/to/php/script"..... )

<?php
    $page = isset($_GET['page']) ? $_GET['page'] : 2;
    $itemWidth = isset($_GET['itemWidth']) ? $_GET['itemWidth'] : 0;
    //Get 24 images from my database
    $link = mysqli_connect("myhost","myuser","mypassw","mybd") or die("Error " . mysqli_error($link)); 
    $query = 'SELECT * FROM images LIMIT 24 OFFSET ' . (($page - 1) * 24);
    $result = $link->query($query);
    $return = null;
    while($image = mysqli_fetch_object($result)) {
        $return .= '<div style="width: ' . $itemWidth . 'px;" class="owl-item"><div><img src="' . $image->path . '" alt="img" /></div></div>';
    }

    mysqli_close($link);       
    // Replace some characters in the return string to they wont mess up javascript
    $return = preg_replace('/\n/s', "", $return);
    $return = preg_replace('/\s\s+/', ' ', $return);
    $return = preg_replace('/\'/', '&rsquo;', $return);
    echo 'cresults = { "html" : \'' . $return . '\', numberOfItems: \'' . $result->num_rows . '\'};'; //echoing the return value will fulfill the Ajax call to this method

That's pretty much it. Easy as pie. Works pretty well too. If the browser resizes and causes the owl items to resize as well, it does reset the carousel back to the first item but I figured out how to add the items to the object so it doesnt mess things up and that is already included in the JavaScript. Let me know if you have any issues and I might be able to help fix them. Been working on this several days and just got this working so I haven't had time to extensively test it but I know it works on mobile phones, both iPhone and Android and works on iPads as well as on desktop browsers. Have fun!

  • @joshua-taylor please see my solution above – pogeybait Jul 28 '15 at 4:23

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!