Image preview on hover over a hyperlink field

05.05.2010 Updated code to adapt the position of the image depending on height and width (and scroll) of the page relative to the image size.


I got this request from Mark:

Hi Alexander,

I did not include the column as a picture because they are to big to display in the list view. For this reason I setup a list with a hyperlink to the image.

Besides it would look terrible having a list that displays all these large pictures in a list view. For that reason, I have been trying to find some way to display an image from a list when a user hovers over a row or column.


IMG
Add this code to a CEWP below the list view, and it will add a hover function to all hyperlinks including an image (add more types to the array “arrOfImageTypes”):

<script type="text/javascript" src="../../Javascript/jquery-1.4.2.min.js"></script>
<script type="text/javascript">

function imagePreview(){
arrOfImageTypes = ['jpg','jpeg','gif','png'];
	$("table.ms-listviewtable td.ms-vb2 a").hover(function(e){
		var href = this.href;
		var img = href.substring(href.lastIndexOf('.')+1).toLowerCase();
		if(href.indexOf('http')==0 && $.inArray(img,arrOfImageTypes)>-1){
		    $("body").append("<img id='preview' src='"+ this.href +"' alt='Image preview' />");	
		}
		var obj = $("#preview");		
		var offset = $(this).offset();
		var winHeight = $(window).height();
		var winWidth = $(window).width();
		var scrollLeft = $(window).scrollLeft();
		var scrollTop = $(window).scrollTop();
		var objHeight = obj.outerHeight();
		var objWidth = obj.width()+15;
		if(((winWidth+scrollLeft)-offset.left)<objWidth){
			offset.left=((winWidth+scrollLeft)-objWidth);
		}
		var maxHeight = (winHeight+scrollTop)-offset.top;
		if(objHeight>maxHeight){
			if(offset.top-scrollTop>objHeight){
				offset.top=offset.top-objHeight-20;
			}
			height = (objHeight<winHeight)?objHeight:winHeight;
		}							 
		obj.css({"position":"absolute","top":(offset.top+20)+"px","left":offset.left+20})
		.fadeIn("fast");						
	},
	function(){
		$("#preview").remove();
	});			
};

// Call the script on page load
$(document).ready(function(){
	imagePreview();
});
</script>

Regards
Alexander

42 Comments on “Image preview on hover over a hyperlink field

  1. I tried this 2 different ways:
    1. added a list to a web part then added a CEWP below the list web part copied the script above and pasted it. Nothing happened.
    Then I thought okay it may not work within a web part so
    2. went to the actual list and edited the page added the CEWP below the actual list and pasted the code. Nothing happened.

    What am I missing?

  2. Hi Alexander:
    This is a wonderful solution!!

    Do you have any way that it can work with a .pdf extension?

    Thanks-

    Charlie Epes
    Buffalo, NY

    1. Hi,
      I do not think this is possible with the logic from the above post. It would be possible to open a new window with the pdf embedded, but this would not be very smooth.

      Alexander

  3. Hi Alexander,

    Great solution. I am using this on the default.aspx for my SharePoint home page on a image. I can see the image popup but noly when entering from the top-left or bottom-right corner. It is not as smooth as in the list. Any reason??

  4. Nope…..I don’t have any custom code other then this. I have a small image 188×180 px for which there is a link which takes to a bigger image 600x500px. This doesn’t preview properly some how……I can send you the code…….

    1. Email me the code and a screenshot of the webpart with the “problem”.

      I will take a look at it tomorrow (I’m om GMT+1 and it is bedtime…).

      Alexander

  5. I have a tasking to hoover over an image and get the information in the comment field of my sharepoint list to display. So instead of hoovering over a link to get a picture; I’d need to hoover over a icon to preview a user comment. Will this solution work for the later?

  6. I have used your code to display a list linking to a library of images. When hovering over the hyperlink “show image”, which is the descriptive text for the pic, it displays two (2) images. One image is placed where a normal tooltip image would be – directly to the right of the cursor. But another second image appears to the far left of the screen slightly lower than the original popup image.

    I downloaded jQuery as in your example. Created a library to hold the files. Added your code to a .txt file and uploaded it to a page. Dropped a CEWP on a page and linked to the .txt file and then hid the CEWP. Dropped the custom list with the image hyperlinks on the same page.

    Any ideas?

  7. Wow. This is something I’ve been looking for…sort of. Would this code adapt to show a preview of wiki pages (from the wiki pages library) when hovering over the link on the sharepoint wiki homepage? If not, do you have such a code?

    1. Hi,
      Sorry for the late reply, but there are so many questions and so little time…

      The answer is no I’m afraid. This solution is for images only.

      Alexander

  8. Hi Alexander, I was woundering whether the code you’ve used here is amendable in terms of adding additional file types to be displayed. I’m relativly new to sharepoint (just over a years experience) and i’m trying to make a few amendments to my site. Alot of the users use a wide range of different image types including Gif. I used your code on my sandbox server and it works beautifully, so I’m hoping i can extend the range.

    Cheers in advance

  9. Hi Alexander,

    is there a way to check if the image exist? I didn’t find a solution to check if e.g. the jpg exists and only when the Image exist show the preview!

    I tried to change your code an build the url to the image (not from the hyperlink itself!), but i can not check if the “generated” url is pointing to a existing image…

  10. Hello Alexander,

    I have a folder called images, and each jpg is labeled by username. I also have a directory that lists each person, which is provided from the directory. Do you know how if I hover over the link to each persons profile page, how can I get the popup to display the image for that person?

    Thanks,

    Aaron

  11. Hi Alexander,

    I am new to sharepoint. Is there any way to use this logic on a wiki page rather than a list to create a hover option for links to images?

    Thank you!

  12. Hi Alexander

    I am creating a new web site for myself, that in itself is a challenge!
    However I came across your site, and I wondered if maybe you can help me?

    I have some type on my site that I need to display images as the user hovers over them.

    Small images, and as the user moves away the image disappears!

    Will your script do this? And if so, how exactly do I get it to do this?

    I am using dreamweaver CS4

  13. Hello Alexander,
    This was a great script. I am using wordpress, and with a little modification I works there as well. I am using the members list plugin and I set it up so that I can mouse over a person’s name and see their photo.

    Thanks,

    Aaron

  14. Hi Alex, would appreciate your response and help:
    How to fix this for Sharepoint 2010?
    Shall it work with 1.7.2 of Jquery?
    Or must I dig in the past to get an 1.4.2 version?

    I get jquery loaded on my page (function). I wil try where to place the alert for the function itself

    Kind regards
    Michael

  15. Hello Alex, today I would appreciate your help. A colleague of mine has heavily customized her page. She has put some boxes on her page (using Sharepoint Designer).

    When I put your above solution on this page, it didnt work. As far as I understand, the script above looks at the wrong “Container”.

    Can you give me a hint to find the correct container(s) or to identify them at the site?

    Kind regards
    Michael

  16. Alex,

    Is it possible to get this to work on a wiki page? Using SP2010. I added a content editor webpart to the page with this script, but nothing happens. I have a single link on the page that is a link to an image.

  17. Hi Alexander,
    I have a contact list on my sp site. And my client asked me to do this.
    When a mouse over a contact name, it will pop up his/her photo.
    I thought your script is a solution for me.
    I create a hyperlink column with a description refers to contact name. each hyper link point to a image file I saved into another library.
    Then I inserted a Content edit web part below the list view, and copied the script including the jquery I saved into the same site, It did not pop up the image, instead it takes me directly to the image file.
    I thought content edit wen part maybe not the right one, and then I inserted a script web part and did the same thing, again the result is the same as before, could you please help me to know what was wrong? thanks in advance.
    Henry

      1. Hi Alexander,
        The page redirect to the image file when I click it.
        The hover over is not working and show no action.
        Thanks for your reply
        Henry

      2. Nothing showing up in the console. no errors , no warnings.
        I use the absolute url for the source of jquery like ‘https://agora.ifes.org/….’
        also I did this on SP 2013 cloud.

  18. This is the script I coped and pasted into script web part. Did I missing anything?
    ———————————–

    function imagePreview(){
    arrOfImageTypes = [‘jpg’,’jpeg’,’gif’,’png’];
    $(“table.ms-listviewtable td.ms-vb2 a”).hover(function(e){
    var href = this.href;
    var img = href.substring(href.lastIndexOf(‘.’)+1).toLowerCase();
    if(href.indexOf(‘http’)==0 && $.inArray(img,arrOfImageTypes)>-1){
    $(“body”).append(“”);
    }
    var obj = $(“#preview”);
    var offset = $(this).offset();
    var winHeight = $(window).height();
    var winWidth = $(window).width();
    var scrollLeft = $(window).scrollLeft();
    var scrollTop = $(window).scrollTop();
    var objHeight = obj.outerHeight();
    var objWidth = obj.width()+15;
    if(((winWidth+scrollLeft)-offset.left)maxHeight){
    if(offset.top-scrollTop>objHeight){
    offset.top=offset.top-objHeight-20;
    }
    height = (objHeight<winHeight)?objHeight:winHeight;
    }
    obj.css({"position":"absolute","top":(offset.top+20)+"px","left":offset.left+20})
    .fadeIn("fast");
    },
    function(){
    $("#preview").remove();
    });
    };

    // Call the script on page load
    $(document).ready(function(){
    imagePreview();
    });

    —————————————–

  19. Sorry this is the complete one I pasted.

    function imagePreview(){
    arrOfImageTypes = [‘jpg’,’jpeg’,’gif’,’png’];
    $(“table.ms-listviewtable td.ms-vb2 a”).hover(function(e){
    var href = this.href;
    var img = href.substring(href.lastIndexOf(‘.’)+1).toLowerCase();
    if(href.indexOf(‘http’)==0 && $.inArray(img,arrOfImageTypes)>-1){
    $(“body”).append(“”);
    }
    var obj = $(“#preview”);
    var offset = $(this).offset();
    var winHeight = $(window).height();
    var winWidth = $(window).width();
    var scrollLeft = $(window).scrollLeft();
    var scrollTop = $(window).scrollTop();
    var objHeight = obj.outerHeight();
    var objWidth = obj.width()+15;
    if(((winWidth+scrollLeft)-offset.left)maxHeight){
    if(offset.top-scrollTop>objHeight){
    offset.top=offset.top-objHeight-20;
    }
    height = (objHeight<winHeight)?objHeight:winHeight;
    }
    obj.css({"position":"absolute","top":(offset.top+20)+"px","left":offset.left+20})
    .fadeIn("fast");
    },
    function(){
    $("#preview").remove();
    });
    };

    // Call the script on page load
    $(document).ready(function(){
    imagePreview();
    });

    1. This have not been tested in SP 2013 so I cannot guarantee it will work, but you can try to change these lines:

      $(document).ready(function(){
      imagePreview();
      });

      Like this:
      setTimeout(function(){
      imagePreview();
      },2000);

      This will delay the function 2 sec and give the list view to render properly.

      Alexander

      1. I replaced “$(document).ready(function(){
        imagePreview();});” WITH ” setTimeout(function(){
        imagePreview();},2000);”

        and I got the following error from F12 CONSOLE:

        HTML1300: Navigation occurred.
        File: AllItems.aspx
        HTML1202: https://ifes365.sharepoint.com/sites/ops/Facility/Lists/HenryTest/AllItems.aspx?PageView=Shared&InitialTabId=Ribbon.WebPartPage&VisibilityContext=WSSWebPartPage is running in Compatibility View because ‘Display intranet sites in Compatibility View’ is checked.
        File: AllItems.aspx
        SCRIPT1014: Invalid character
        File: AllItems.aspx, Line: 686, Column: 21
        [1][SerializeToClient][ScriptApplicationManager state initialized.]
        [2][ctl00_PlaceHolderSearchArea_SmallSearchInputBox1_csr:Srch.SearchBox][Initialize][]
        [3][No_ID:Srch.ScriptApplicationManager][RegisterClientControl][Adding SearchBox ‘ctl00_PlaceHolderSearchArea_SmallSearchInputBox1_csr’ to query group ‘MasterPage’]
        [4][inplaceSearchDiv_WPQ2:Microsoft.SharePoint.Portal.ListSearchBox][Initialize][]
        [5][inplaceSearchDiv_WPQ2:Microsoft.SharePoint.Portal.ListSearchBox][RenderControl][]

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.