modals & data-attibutes

Create detailed views dynamically using Bootstrap 4, modals, data-attributes and a bit of javascript

This technique works well with the AJAX portfolio

Bootstrap 4 dynamic modals using data-attriubes

This technique can apply to much more than just modals.

Too lazy to right-click and view source?? Here's the code:

<!-- Modal -->
<div class="modal fade" id="galleryModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="galleryTitle">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
      <div class="modal-body">
          <img src="" alt="" class="img-fluid">
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>

Here's the link / modal trigger with data-attibutes:

<figure data-title="no way to treat a bike" data-caption="You can put a much longer caption using this." data-src="images/winter-IMG_3693.jpg">
  <a href="#" data-toggle="modal" data-target="#galleryModal">
    <img src="images/winter-IMG_3693.jpg" alt="" class="img-fluid">
  <figcaption>winter captions</figcaption>

And here's the javascript.

//load modal content dynamically
  $('#galleryModal').on('', function (event) {
    var figure = $(event.relatedTarget).parent(); // Button that triggered the modal
    var title ='title'); // Extract info from data-* attributes
    var src ='src');
    var caption ='caption');

    // If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
    // Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
    var modal = $(this);
    modal.find('.modal-body img').attr("src", src);
    modal.find('.modal-body figcaption').text(caption);

Oh... and this little bit of .css to fix the closing x alignment

#galleryModal .modal-title{
  display: inline-block;