Insert an image into a modal dialog

Viewed 922

I want to insert an image in Modal but I need to use the value of the variable data-image as it will change according to the value of the image.

<script type="text/javascript">
        $('#myModal').on('show.bs.modal', function (event) {
            var button = $(event.relatedTarget) // Button that triggered the modal
            var title = button.data('title')
            var overview = button.data('overview')
            var image = button.data('image')
            var url = "<img src='https://image.tmdb.org/t/p/w600_and_h900_bestv2/+image+'></img>"
            var modal = $(this)
            modal.find('#title').text(title)
            modal.find('#image').attr('src',url)
            modal.find('#overview').text(overview)
        })
    </script>
                                <a href="#" role="button" data-id="{{$item['id']}}" data-title="{{$item['title']}}" data-image="{{$item['imagem']}}" data-overview="{{$item['overview']}}" data-toggle="modal" data-target="#myModal">

<div class="modal fade bd-example-modal-lg" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLongTitle"><div id="title"></div></h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <p><div id="image"></div></p>
            <p><div id="overview"></div></p>
        </div>
    </div>
</div>

I tried to use some shapes like text, val, innerhtml, but it didn't work. What is the best way to make it work what I need?

2 Answers

You need to use an img element as oppose to a div to set display your img and other content dynamically in your modal.

The reason its not working is DOM content is ready and you are applying styles to a div and it can not load an image asynchronously thats why you are not seeing anything.

I have added demo data and few other button to show that its all working now with different data coming from data-attributes.

Live Working Demo:

$('#myModal').on('show.bs.modal', function(event) {
  var button = $(event.relatedTarget) // Button that triggered the modal
  var title = button.data('title')
  var overview = button.data('overview')
  var image = button.data('image')
  var modal = $(this)
  modal.find('#title').text(title)
  modal.find('#image').attr('src', image)
  modal.find('#overview').text(overview)
})
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

<a href="#" role="button" data-id="Foo" data-title="Foo" data-image="https://via.placeholder.com/150" data-overview="Foo" data-toggle="modal" data-target="#myModal">Click Me</a>
<br>
<a href="#" role="button" data-id="Bar" data-title="Bar" data-image="https://via.placeholder.com/300" data-overview="Bar" data-toggle="modal" data-target="#myModal">Click Me 2</a>
<br>
<a href="#" role="button" data-id="Example" data-title="Example" data-image="https://via.placeholder.com/350" data-overview="Example" data-toggle="modal" data-target="#myModal">Click Me 3</a>

<div class="modal fade bd-example-modal-lg" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLongTitle">
          <div id="title"></div>
        </h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <p><img src="" id="image" /></p>
        <p>
          <div id="overview"></div>
        </p>
      </div>
    </div>
  </div>

First, understand what a modal dialog is: it is just a div (with content) that is positioned so that it sits on top of the rest of the page, usually accompanied by another div that sits directly underneath it and partially darkens the rest of the page while preventing the user from clicking on anything underneath. These two divs begin hidden, but can be displayed based on user activity, and then re-hidden.

The modal word indicates that this div structure has the focus - the user cannot interact with any other part of the page until the modal dialog is closed. This is accomplished via that second (overlay) div that is height/width 100% and is positioned (via z-index) to stack between the dialog and the rest of the page.

The important thing to note is that they are just ordinary div structures that exist on the page - or that are added to the page - at will. That means, you can change the content (text or html) inside the modal div structure as easily as you can change the content of any other div. There is nothing different about a modal div structure at all.

Bootstraps modal dialogs are exactly the same, but they include some extra sizzle that add some extra visual coolness and that make them a bit easier to work with. Other than that, they are exactly like self-made modal dialogs - which are exactly like ordinary div structures.

To demonstrate, we'll create a super-simple home-made modal dialog and use it to do what you request.

Note the following about the home-made modal dialog:

(a) We use position:fixed or position:absolute to remove the modal div structure from the usual HTML flow - allowing it to sit on top of the rest of the page.
(b) We use z-index to position the modal div structure ABOVE the rest of the page
(c) We add a second div (the "overlay") that sits on top of the page, but underneath the modal. Its purpose is to darken the page underneath the modal dialog and to prevent the user from clicking anything on the page until they finish with the dialog.

$('button').click(function(){
  let img = $('#modal').data('image');
  $('#modal-content').html(`<img src="${img}" />`);
  $('#overlay, #modal').fadeIn();
});

$('#modal-close').click(function(){
  $('#overlay, #modal').fadeOut();
});
#overlay{z-index:998;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,.7);}

#modal{z-index:999;position:fixed;top:15vh;left:25vw;width:50vw;height:30vh;}

#modal-close{position:absolute;top:0;right:0;padding:10px;font-size:2em;border:1px solid grey;}
#modal-close:hover{color:dodgerblue; border:1px solid dodgerblue;cursor:pointer;}

#overlay, #modal{display:none;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id='overlay'></div>
<div id='modal' data-image='http://placekitten.com/400/300'>
   <div id='modal-close'>X</div>
   <div id='modal-content'></div>
</div>
<button>Show Modal</button>

References:

Easiest way to use a div as a modal dialog with jQuery

Related