Reputation: 205
I've got 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 mouseover I want to display a thumbnail image of the product in a div #preview.
I don't want to hardcode the jquery for each image. Rather I'd like to write JQuery that would grab the image location and insert into the DOM. I have no idea how I would mark up the HTML to include the image location. Any ideas?
Upvotes: 6
Views: 19318
Reputation: 112857
I'd suggest using the new HTML5 data attributes, like so:
<a href="chair.php" data-thumbnail-src="chair.jpg">CHAIR</a>
Then you could set up the 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 higher, I believe $(this).data("thumbnail-src")
will also work.
Upvotes: 7
Reputation: 1968
its is old , but i got here with google search . i believe the best solution would be this : http://james.padolsey.com/demos/imgPreview/full/
Upvotes: 2
Reputation: 19465
Hopefully this is a decent solution. Im using the JQuery Metadata plugin
Here is the stuff live : 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:
<li>
named pic {url:'something'}
.""
. Here you should set it to a NONE pic or do something else.Hope this helped.
Upvotes: 1