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



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


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



<!DOCTYPE HTML>
<html>
<head>
<script src="jquery.js"></script>
<style text="text/css">
.hoverImage {
position: absolute;
width: 200px;
left: 500px;
top: 200px;
}
</style>
</head>
<body>
<script>
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,
},200);
}

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,
},200);
}

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

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




No comments:

Post a Comment