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?
The hover function is used to get the hover event. On the hover event, we can load image attribute to a new image that we want to load on hover. In the following simple example, I write the event function and change the src of the image to a new image. You need to make sure to import jQuery JS.
The hover() method specifies two functions to run when the mouse pointer hovers over the selected elements. This method triggers both the mouseenter and mouseleave events. Note: If only one function is specified, it will be run for both the mouseenter and mouseleave events.
image:hover {display:none;} .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With