How can I make the Bootstrap js carousel automatically cycle as soon as the page loads?

前端 未结 15 1509
花落未央
花落未央 2020-12-04 21:53

Using bootstrap.js version 2.02

I\'m trying to get the Twitter Bootstrap Carousel to automatically cycle as soon as someone visits my site. Right now, the auto cycl

相关标签:
15条回答
  • 2020-12-04 22:34

    A quick and dirty solution is to programmatically click the button on document ready:

    $(function() {
      $(".right.carousel-control").click();
    });
    

    BTW: make sure you load jQuery before the other scripts referring to $, right now you have two Uncaught ReferenceError: $ is not defined because you call $ on line 101 and 182, but jquery is first loaded on line 243.

    I would recommend using a tool like firebug or developer tool (chrome/safari) to catch these errors.

    EDIT: I think you already have a working solution, but because you use jquery before it's loaded it doesn't work.

    0 讨论(0)
  • 2020-12-04 22:34

    While there undoubtedly are correct answers here, I just wanted to add that you can reproduce the exact behavior as the poster describes by adding errors to your code. Remove semicolons or the ending script tag for example, and the carousel wont autoplay anymore.

    So the first thing you should do is to look for errors in your javascript console!

    0 讨论(0)
  • 2020-12-04 22:42

    In Bootstrap 3.0, this can be accomplished by adding a 'data-ride' attribute to the carousel container:

    ...
    0 讨论(0)
  • 2020-12-04 22:44

    In Bootstrap 3.0, this can be accomplished by adding a 'data-ride' attribute to the carousel container:

    <div id="my-carousel" class="carousel slide" data-ride="carousel">
        <div class="carousel-inner">
            ...
        </div>
    </div>
    

    https://github.com/twbs/bootstrap/blob/v3.0.0/js/carousel.js#L210

    0 讨论(0)
  • 2020-12-04 22:46
    $('.carousel').carousel({
      interval: 2000
    })
    
    0 讨论(0)
  • 2020-12-04 22:46

    This is the solution which worked for me, based on Jesse Carter's answer to this question. I have no idea why this works, but for some reason it needs 2 calls, one inside the document dot ready and the other outside. If I remove either of them then something goes wrong, eg the pause functionality cant be made to work properly, or the automatic cycling. Further to this the interval only seems to work inside the doc.ready. Comments from javascript heads most welcome ;-) but I suspect that this area of T.B. is not entirely bug free! I'm using 2.0.2 which I know is a little bit behind ( current version now is 2.0.4) but I don't see any changes to this area

    jQuery(document).ready(function () {
        jQuery('#myCarousel').carousel(
        {
        interval:2000
        });
    });
    
    jQuery('#myCarousel').carousel();
    
    0 讨论(0)
提交回复
热议问题