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

Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: