Change Background Image Position using jQuery

I was working on an app recently and one of the requirements was to change the background image position of a paragraph element using jQuery. The app had a deck of cards (images) laid one on top of the other and doing this in the application made a lot of sense. I cannot reveal much details about the app but in this post, I will show you how simple it is to change the position of an element’s background image in jQuery, when the mouse is hovered over it.

Use the following HTML where a paragraph has a background image as shown below:

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Change Background Image Position (from DevCurry.com)</title>
<style type="text/css">
p
{
background-image : url(http://www.devcurry.com/296396.jpg 
background-repeat: no-repeat;
height: 600px; 
border: 1px solid black;         
}
</style>
<script type="text/javascript"
src="http://ajax.microsoft.com/ajax/jquery/jquery-1.5.2.min.js">
</script>

<script type="text/javascript">
$(function () {
$('#pone').hover(function () {
$(this).css('backgroundPosition', 10);
}, function () {
$(this).css('backgroundPosition', '');
});
});
</script>
</head>
<body>
<p id="pone"></p>

</body>
</html>
;

The .hover() method binds handlers for both mouseenter and mouseleave events. We are simply adding behavior to the para element and changing the backgroundPosition when the mouseenter event occurs.

See a Live Demo

No comments:

Post a Comment