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="" >
<title>Change Background Image Position (from</title>
<style type="text/css">
background-image : url( 
background-repeat: no-repeat;
height: 600px; 
border: 1px solid black;         
<script type="text/javascript"

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


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: