<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!------ Include the above in your HEAD tag ---------->
<div class="container" style="margin-top: 7%">
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group image-preview">
<div class="input-group mb-3">
<div class="custom-file">
<div class="image-preview-input">
<input type="file" class="custom-file-input" accept="image/png, image/jpeg, image/gif" id="customFile" name="img" /> <!-- rename it -->
<label class="custom-file-label" for="customFile"><i class="far fa-images"></i></label>
</div>
</div>
<div class="input-group file-load" style="display:none;">
<input type="text" class="form-control image-preview-filename" disabled="disabled">
<div class="input-group-append">
<button type="button" class="btn btn-default image-preview-clear" style="display:none;">
<i class="far fa-trash-alt"></i>
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
$(document).on('click', '#close-preview', function(){
$('.image-preview').popover('hide');
// Hover befor close the preview
$('.image-preview').hover(
function () {
$('.image-preview').popover('show');
},
function () {
$('.image-preview').popover('hide');
}
);
});
$(function() {
// Create the close button
var closebtn = $('<button/>', {
type:"button",
text: 'x',
id: 'close-preview',
style: 'font-size: initial;',
});
closebtn.attr("class","close pull-right");
// Set the popover default content
$('.image-preview').popover({
trigger:'manual',
html:true,
title: "<strong>Vista previa</strong>"+$(closebtn)[0].outerHTML,
content: "There's no image",
placement:'left'
});
// Clear event
$('.image-preview-clear').click(function(){
$('.image-preview').attr("data-content","").popover('hide');
$('.image-preview-filename').val("");
$('.image-preview-clear').hide();
$('.image-preview-input input:file').val("");
$(".image-preview-input-title").text("Elegir");
$(".custom-file").show()
$('.file-load').hide()
});
// Create the preview image
$(".image-preview-input input:file").change(function (){
$(".custom-file").hide()
var img = $('<img/>', {
id: 'dynamic',
width:250,
height:200
});
var file = this.files[0];
var reader = new FileReader();
// Set preview image into the popover data-content
reader.onload = function (e) {
$(".image-preview-input-title").text("Cambiar");
$(".image-preview-clear").show();
$(".image-preview-filename").val(file.name);
img.attr('src', e.target.result);
$(".image-preview").attr("data-content",$(img)[0].outerHTML).popover("show")
}
$('.file-load').show()
reader.readAsDataURL(file);
});
});