Bootstrap v5 modal show issue

2

I decided to go ahead and update my site to the latest version of Bootstrap, version 5.0 and am having difficulty getting modals to work. Reading the migration guide said nothing about breaking modals and my site worked perfectly before. My code uses javascript/jQuery to fire off the modal after the ajax loads the text. The ajax part still works fine, but it's not firing the modal after it retrieves it. I'm using the latest bootstrap.bundle.min.js.

$( document ).ready(function() {
$('.hourModal').click(function(){
    var obj_id = $(this).data('id');
    $.ajax({
        url: 'ajax-multi.php',
        type: 'POST',
        data: {obj_id: obj_id,role:'some_role'},
        //dataType: 'html',
        success: function(response){ 
            $('.modal-body').html(response);
            //$('#hourModal').modal('show'); //Old way that worked great
            var hourModal = new bootstrap.Modal(document.getElementById('hourModal'));
            hourModal.show(); // New way I tried from the Bootstrap documentation
        }
    });
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-p34f1UUtsS3wqzfto5wAAmdvj+osOnFyQFpp4Ua3gs/ZVWx6oOypYoCJhGGScy+8" crossorigin="anonymous"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-wEmeIV1mKuiNpC+IOBjI7aAzPcEZeedi5yW5f2yOq55WWLwNGmvvx4Um1vskeMj0" crossorigin="anonymous">

<!-- Button -->
<button type="button" class="btn btn-secondary btn-sm py-0 me-1 hourModal" data-id="1">Blocks</button>

<!-- Modal -->
<div class="modal fade" id="hourModal" tabindex="-1">
  <div class="modal-dialog modal-xl">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Object Times</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close">  </button>
      </div>
      <div class="modal-body">
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

The error I get is: Uncaught TypeError: BACKDROP: Option "rootElement" provided type "null" but expected type "element".

Any help is greatly appreciated!

UPDATE: As described below, I had to move bootstrap.min.js to the end of the page, after </body> and leave where I call jquery.min.js at the top in the header. Anyone have any idea why it has to be done this way?

Share
Improve this question
1
  • You are mixing php and JS which is never a good idea. – SuperDJ May 7 at 19:26

Comments

Popular posts from this blog

Meaning of `{}` for return expression

Get current scroll position of ScrollView in React Native

flutter websocket connection issue