简体   繁体   中英

How to delay display of Bootstrap 3 modal after click

I'm trying to delay the display of a Bootstrap modal after the user has clicked on a trigger button:

<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
  Launch demo modal
</button>

Looking at the Bootstrap 3 documentation I can see there is a show event that can be hooked to but am not sure how to introduce a 3 second delay before the modal appears on screen. Hoping someone can help?

Ref: http://getbootstrap.com/javascript/#modals

You can delay the click of the trigger button, then activate the modal directly:

$('[data-toggle=modal]').on('click', function (e) {
    var $target = $($(this).data('target'));
    $target.data('triggered',true);
    setTimeout(function() {
        if ($target.data('triggered')) {
            $target.modal('show')
                .data('triggered',false); // prevents multiple clicks from reopening
        };
    }, 3000); // milliseconds
    return false;
});

http://jsfiddle.net/mblase75/H6UM4/

Use .on() to hook into the event:

var isFirstShowCall = false;

$('#myModal').on('show.bs.modal', function (e) {
    isFirstShowCall = !isFirstShowCall; // Prevents an endless recursive call
    if(isFirstShowCall) {
            e.preventDefault(); // Prevent immediate opening
            window.setTimeout(function(){
                $('#myModal').modal('show');
            }, 3000)
    }
});

http://jsfiddle.net/G9XeA/

window.setTimeout(function() {
   $('#myModal').modal('show');
}, 5000)

For demo I used 5000 mini seconds. You can used it as per your need...

If any of those above method does't work, give this method a try. It will work perfectly.

$(window).ready(function() {
   setTimeout(function(){
       $('#myModal').modal('show');
   }, 2000);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM