Last active
December 10, 2020 10:48
-
-
Save dinhanhthi/fb81766d0070d15d5ad2fc239643fb3b to your computer and use it in GitHub Desktop.
Click to zoom photo using Bootstrap 4
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- Put below scripts in that order before </body> tag. --> | |
<!-- jquery 1.10.1 --> | |
<script src="https://code.jquery.com/jquery-1.10.1.min.js" integrity="sha256-SDf34fFWX/ZnUozXXEH0AeB+Ip3hvRsjLwp6QNTEb3k=" crossorigin="anonymous"></script> | |
<!-- bootstrap scripts --> | |
<!-- How to use: add class "pop" to <img> --> | |
<img src="/path/to/image" class="pop" > | |
<!-- div of zoomed image: Add below before </body> --> | |
<div class="modal fade" id="imagemodal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> | |
<div class="modal-dialog modal-dialog-centered modal-lg"> | |
<div class="modal-content"> | |
<div class="modal-body"> | |
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button> | |
<img src="" class="imagepreview" style="width: 100%;" > | |
</div> | |
</div> | |
</div> | |
</div> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Fit to the size of the view screen | |
jQuery(document).ready(function($){ | |
// add more attributes to the img.pop | |
$('.pop').attr("data-toggle", "tooltip"); | |
$('.pop').attr("data-placement", "top"); | |
$('.pop').attr("title", "Click to see a bigger photo."); | |
// current view port size | |
var wW = $(window).width()*0.9; | |
var wH = $(window).height()*0.9; // max display | |
$('[data-toggle="tooltip"]').tooltip(); | |
$('.pop').on('click', function() { | |
// real size of the photo | |
var rW = $(this).find('img')[0].naturalWidth; | |
var rH = $(this).find('img')[0].naturalHeight; | |
var cW, cH; // photo's will be set to this size! | |
cW = rW; cH = rH; // initial setting | |
if (rH < wH){ | |
if (rW > wW){ | |
cW = wW; cH = wW*rH/rW; | |
} | |
} else{ | |
if (rW < wW){ | |
cH = wH; cW = wH*rW/rH; | |
} else if(wW*rH/rW < wH){ | |
cW = wW; cH = wW*rH/rW; | |
} else{ | |
cH = wH; cW = wH*rW/rH; | |
} | |
} | |
// Show max photo's size if it's smaller than the current view port. Otherwise, it scale photo to the size of view port. | |
$('.modal-dialog')[0].style.width = cW + "px"; | |
$('.modal-dialog')[0].style.height = cH + "px"; | |
$('.imagepreview').attr( | |
'src', $(this).find('img').attr('src') | |
); | |
$('#imagemodal').modal('show'); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment