How to make a popover that shows an enlarged version of a dynamic image using JQuery?

Viewed 125

I have to display a popover containing an enlarged version of a dynamic image that gets added via a file input #insert-image but I am not sure how to go about doing this since the image is dynamic and the url of the image changes depending on what is selected by using the file input. The code below basically just adds the image that is selected to a table cell.

var imagePrep = $("#insert-image").val().replace(/C:\\fakepath\\/i, 'images/');
$('td:contains("image")').html("<img src=" + imagePrep + " alt='selected-image' class='image'>");

2 Answers

I managed to get it working myself by adding a few attributes data-toggle='popover'" + "data-img=" + imagePrep + ">" with imagePrep being my variable. I also had to add a mouseover function to my image and within that function I added the popover using the popover function (ps. If you get an error saying that the popover function doesn't exist just make sure to have the bootstrap scripts in your html file, you cn find the bootstrap scripts on the bootstrap website).

This is a solution that solved my problem:

$('td:contains("image")').html("<img src=" + imagePrep + " alt='selected-image' class='image' data-toggle='popover'" + "data-img=" + imagePrep + ">").on('mouseover', function() {
      $('[data-toggle="popover"]').popover({
        trigger: 'hover',
        html: true,
        content: function() {
          return '<img class="img-fluid" src="' + $(this).data('img') + '" />';
        },
        title: 'Enlarged Image'
      });
    });

Hope this helps.

Just copy the commented url and pest in text box dynamic image is created. You also use both jQuery and Javascript attributes. Below is the example:

<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
</head><!--from   ww  w  . ja  v  a2  s.c o  m-->
<body>
 <div>
 <input type="text" id="insert-image" />
 <input type="button" id="insert" value = "insert" /> 
 </div>

  <div id="imgwrapper"></div>

  <script>
$(document).ready(function()
{
$("#insert").on("click",function(){
 
    img = document.createElement("img"); 
    
   // img.src = "http://www.java2s.com/style/download.png"; 
    img.src = $('#insert-image').val();
    img.mouseover = function(e){alert(e);}  
    $('#imgwrapper').append(img); 
      $("#imgwrapper").on("mouseover",function(){
 alert("TEST");
 }); 
    });
});
    </script>
</body>
</html>

Related