Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setTimeout with Bootstrap Modal not displaying after time out

I'm trying to delay showing a Bootstrap modal until 5 seconds have passed. Here is the section of my code. It seems write from what I have read on MDN. The modal does not appear after any amount of time. Any help would be appreciated.

var timeout;
  function modalAlert(message){
        $("#myModalLabel").text("Hey Look!")
        $('.modal-body').html("<img src='"+message+"'>");
        timeout = window.setTimeout(showModal,5000);

  }
  function showModal(){
    console.log("HERE")
    $("#myModal").modal('show')
  }

Vijay Ramamurthy helped me find the solution:

var timeout;
  function modalAlert(message){
        $("#myModalLabel").text("Hey Look!")
        $('.modal-body').html("<img src='"+message+"'>");
        window.setTimeout(function(){showModal();},5000);

  }
  function showModal(){
    console.log("HERE")
    $("#myModal").modal('show')
  }
like image 208
Nick Avatar asked Jan 13 '23 09:01

Nick


1 Answers

Use the "shown" event handler to register a timeout on the modal and then hide it. You can chain the functions together since it's a jQuery plugin.

$("#myModal").modal("show").on("shown", function () {
    window.setTimeout(function () {
        $("#myModal").modal("hide");
    }, 5000);
});
like image 89
Andy Brudtkuhl Avatar answered Jan 19 '23 12:01

Andy Brudtkuhl