There are plenty of ways. But let me inspect how this particular site implements it.
Check the source code of the webpage, for each image, the HTML is like:
<div class="item" data-w="270" data-h="180">
<a href="https://stackoverflow.com/en/pine-forest-branch-road-conifer-463469/">
<img src="/static/uploads/photo/2014/09/27/13/36/pine-463469__180.jpg" class="preview_img" data-url="/static/uploads/photo/2014/09/27/13/36/pine-463469_640.jpg" data-width="492.307692308" data-height="327.692307692" alt="Pine, Forest, Branch, Road, Conifer" title="Pine, Forest, Branch, Road, Conifer">
<em>Pine, Forest, Branch, Road, Conifer</em>
</a>
</div>
Here you can see, they show the smaller image first, which is /static/uploads/photo/2014/09/27/13/36/pine-463469__180.jpg
, and the larger image is stored in the data
attribute of the <a>
tag, which is data-url="/static/uploads/photo/2014/09/27/13/36/pine-463469_640.jpg"
. In this way, you can first load the small image to save bandwidth.
Its class preview_img
is for selecting all preview images. You can see its functionality as follow. The javascript file they are using is http://pixabay.com/static/js/base6.min.js
, which is a min
file. But can still search preview_img
to find the code making effect:
var hover_timeout, no_preview=getCookie("no_preview");
$(document).on("mouseenter", ".preview_img", function(e) {
var o=$(this), i=e.pageX, n=e.pageY;
if(!no_preview || null != o.data("force-preview")) {
var r = o.attr("title");
r && (o.data("title",r), o.attr("title","")),
hover_timeout = setTimeout(function() {
var e=o.data("width"),
r=o.data("height"), a=r,
s=o.data("cut"),
c=o.data("title");
if(s&&(a+=s),!(e+30>ww||r+30>wh||e+30>wh||r+30>ww)) {
preview = $('<div class="open_preview_img" style="z-index:'+(max_zindex+10)+
'"><div style="position:relative;overflow:hidden;width:'+(e+2)+"px;height:"+(r+2)+
'px"><img style="width:'+e+"px;height:"+a+'px" src="'+o.attr("src")+'"><img style="width:'+e+'px" src="'+o.data("url")+'"></div>'+(c?"<em>"+c+"</em>":"")+"</div>").prependTo("body");
...
So you can see that they bind delegate the event mouseenter
to all images with class preview_img
. And then populate the HTML code and .prependTo("body")
. And you can see the src
attribute of the image is o.attr("src")
, which is the url of larger image.
Most of the code here is to calculate the position/size information of the large image. Depending on you application, you can customize.