CHAIR
  • How to display image when user hovers over link using jQuery

    I have a list of products.

    <ul> <li><a href="chair.php">CHAIR</a></li> <li><a href="table.php">TABLE</a></li> <li><a href="sofa.php">SOFA</a></li> <li><a href="bookshelf.php">BOOKSHELF</a></li> <ul> 

    On hover, I want to display the product thumbnail in the #preview div.

    I do not want to hard code jquery for each image. Rather, I would like to write jQuery that would capture the location of the image and embed it in the DOM. I have no idea how to tag the HTML to include the location of the image. Any ideas?

    +4
    source share
    3 answers

    I would suggest using new HTML5 data attributes , for example:

     <a href="chair.php" data-thumbnail-src="chair.jpg">CHAIR</a> 

    Then you can configure jQuery code as follows:

     $(function () { var $preview = $("#preview"); $("ul#products a").hover(function () { $preview.attr("src", $(this).attr("data-thumbnail-src")); }, function () { $preview.attr("src", ""); }); }); 

    In jQuery 1.4.3 and above, I believe $(this).data("thumbnail-src") will work as well.

    +6
    source

    I hope this is a worthy solution. Im using jQuery metadata plugin

    Here is the live material: http://jsfiddle.net/giddygeek/VqL65/14/

    Html:

     <script type="text/javascript" src="https://github.com/jquery/jquery-metadata/raw/master/jquery.metadata.js"></script> <ul class="pics"> <li class="pic {url:'chair.jpg'}"> <a href="chair.php">CHAIR</a></li> <li class="pic {url:'table.jpg'}"> <a href="table.php">TABLE</a></li> <li> <a href="sofa.php">SOFA</a></li> <li> <a href="bookshelf.php">BOOKSHELF</a></li> <ul> <div id="preview"> <img src="" /> <div/> 

    JQuery

     $(document).ready(function() { $("ul.pics li").hover( function() {//on hover over var data = $(this).metadata();//get the metadata if(data.url) {//check if it exists $("#preview img").attr("src",data.url)//set the url to it } }, function() {//on hover OUT $("#preview img").attr("src","");//set the img src to nothing } ); } ); 

    Notes:

    • I heard that it is W3C compatible and may be Html5 compatible
    • Add a class for each <li> named pic {url:'something'} .
    • Set the URL of your favorite image.
    • In jQuery, freezing disables img src β†’ "" . Here you have to set it to NONE pic or do something else.
    • Oh and download the metadata plugin (I used the raw link from github)

    Hope this helps.

    0
    source

    its old but i got here with google search. I believe the best solution would be the following: http://james.padolsey.com/demos/imgPreview/full/

    0
    source

    All Articles