Search code examples
htmljquerycssbootstrap-4bootstrap-modal

Bootstrap 4 modal close and redirect url in new tab


I want to open a bootstrap modal when the site loads and close it after 3 seconds, and when it closes it redirects to a new URL in a new tab. this is code:

<div class="modal fade" id="myModal1">
      <div class="modal-dialog">
        <div class="modal-content">
           <button type="button" class="close" data-dismiss="modal">&times;</button>
           <div class="model-box">
             <div class="row">
                 <img src="img/mod/pop-header.svg" alt="" class="model-img1">
             </div>          
             <a href="#" class="model-btn" target="_blank">Get Your 100% Bounus</a>
           </div>
        </div>
      </div>
    </div>
<script type="text/javascript">
  $(document).ready(function(){
// Open modal on page load
$("#myModal1").modal('show');
//redirect after 5seconds
setInterval(function(){
   $("#myModal").modal('hide');
  window.open('http://127.0.0.1:30008/','_blank');},3000);
  setTimeout(function(){
  $('#myModal1').modal('hide')
}, 3000);

})
  </script>

currently i use this code but it redirects after 3 scound continuously but i want to redirect only once when the modal is closed.


Solution

  • You are using setInterval which would run every time interval, for one-time occurrence you should use setTimeout, which would run once after the specified time

    Try Below Snippet

        <div class="modal fade" id="myModal1">
          <div class="modal-dialog">
            <div class="modal-content">
               <button type="button" class="close" data-dismiss="modal">&times;</button>
               <div class="model-box">
                 <div class="row">
                     <img src="img/mod/pop-header.svg" alt="" class="model-img1">
                 </div>          
                 <a href="#" class="model-btn" target="_blank">Get Your 100% Bounus</a>
               </div>
            </div>
          </div>
        </div>
    <script type="text/javascript">
      $(document).ready(function(){
    // Open modal on page load
    $("#myModal1").modal('show');
      setTimeout(function(){
      $('#myModal1').modal('hide');
       window.open('http://127.0.0.1:30008/','_blank'); // Added redirect in setTime out and removed the setInterval, which would run on each time after the specified duration.
    }, 3000);
    
    })
      </script>