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




About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: