Wednesday, May 16, 2012

Creating custom jQuery class

I am creating a photo gallery for my website. I want a grid of the photos displayed when the page loads. Then when the user hovers over each photo, the photo enlarges a little.

I created the javascript for the hovering, but I do not know how to properly package this into a class.

Basically, I want to just create a list like this

<li><img src="img1.jpg" /></li>
<li><img src="img2.jpg" /></li>

And then it automatically creates each image with my hovering mechanism already in place.
Here is my code thus far.

<script src="jquery.js"></script>
<style text="text/css">
.hoverImage {
position: absolute;
width: 200px;
left: 500px;
top: 200px;
var originalWidth;
var originalHeight;

function onHover() {
originalWidth = $(this).width();
originalHeight = $(this).height();

$(this).stop(false, true).animate({
left: $(this).offset().left-(Math.floor(originalWidth/4)),
top: $(this).offset().top-(Math.floor(originalHeight/4)),
width: 300,

function offHover() {
$(this).stop(false, true).animate({
left: $(this).offset().left+(Math.floor(originalWidth/4)),
top: $(this).offset().top+(Math.floor(originalHeight/4)),
width: 200,

$(document).ready(function() {
$("img").hover(onHover, offHover);

<img class="hoverImage" src="Test.jpg"/>

No comments:

Post a Comment