|
Incredibly simple JQuery image change on mouse over effect |
I was recently asked in conversation if it would be possible to have a list of items, and when a user mouse'd over the headers in the list, an image effect happened, IE a thumbnail image was displayed. I figured this would be an ideal use for JQuery, so this article is how to write an incredibly simple JQuery image change.
There is a full demo of this here: JQuery mouse over demo
Here is the full code for this example; I'll go into the breakdown beneath it.
2
3<s/cript type="text/javascript">
4$(document).ready(function() {
5
6 $('dt').mouseover(function() {
7
8 var image = $(this).attr('id');
9 $('#previewImage').attr('src', 'pathToImage' + image + '.jpg');
10 });
11});
12</s/cript>
13
14<style>
15 .data{float: left; width 300px;}
16 .previewImage-div {float: right; border: 1px ##000 solid;}
17</style>
18
19<div class="previewImage-div">
20<b>Image Preview</b><br>
21<img id="previewImage">
22</div>
23
24<div class="data">
25
26<dl>
27 <dt id="imageIdVariable1"><b>Title text 1</b></dt>
28 <dd>Description text 1</dd>
29
30 <dt id="imageIdVariable2"><b>Title text 2</b></dt>
31 <dd>Description text 2</dd>
32
33 <dt id="imageIdVariable3"><b>Title text 3</b></dt>
34 <dd>Description text 3</dd>
35</dl>
36
37</div>
Firstly we go and get the JQuery library from Google.
Our displayable code is a definition list 'dl' html element. Whenever a user mouse's over a definition term 'dt' our JQuery code will pick up the id value of the selected element and change the source of the 'previewImage'.
Initially the 'previewImage' image element does not even have a source attribute, so will not display at all.
The JQuery script will load when the DOM is finished loading. The first line simply gets the id of the 'dt' element being mouse'd over. The second line changes the source attribute of the 'previewImage' image html element. It is building a URL here, so change this to whatever format you store images in.
The demo below is being populated from a database, so the source is a little more dynamic looking.
There is a full demo of this here: JQuery mouse over demo