Jquery Course

Animate background position
Getting background position

This tutorial shows how to change, animate, and get the position of a background image in HTML elements with jQuery.
If you want to simply set, or change the background position, use this syntax:
$(selector).css({ backgroundPosition: 'Xval Yval' })
- Xval - represents the value for the horizontal position.
- Yval - represents the value for the vertical position.

Examples change background position

1. When click on a button, places the background image in right-bottom.
<style type="text/css">
#idex1 {
 width:320px;
 height:80px;
 background:url('image.jpg') 0 0 no-repeat;
 border:1px solid blue;
}
</style>
<div id="idex1"></div>
<button id="bex1">Click</button>
<script type="text/javascript"><!--
$('#bex1').click(function(){
  $('#idex1').css({backgroundPosition: '100% 100%'});
});
--></script>

Demo:

2. When mouse cursor is over an element, center its background image horizontally, and 25 pixels from top. On mouse out, places the background to top-left.
<style type="text/css">
#idex2 {
 width:320px;
 height:80px;
 background:url('image.jpg') 0 0 no-repeat;
 border:1px solid blue;
}
</style>
<div id="idex2"></div>
<script type="text/javascript"><!--
$('#idex2').mouseover(function(){
  $(this).css({backgroundPosition: '50% 25px'});
});
$('#idex2').mouseout(function(){
  $(this).css({backgroundPosition: '0 0'});
});
--></script>

Demo (place the mouse cursor over the block):

3. When click on a button, alternate the background position, horizontally right and left:
<style type="text/css"><!--
#idex3 {
 background: url('image.jpg') 0 center no-repeat;
 width:400px;
 height:80px;
 border:1px dashed green;
}
--></style>
<div id="idex3"></div>
<button id="bex3">Click</button>
<script type="text/javascript"><!--
// https://coursesweb.net
var ix = 1;
$('#bex3').click(function() {
  $('#idex3').css({ 'background-position': (100 * (ix % 2)) +'% 50%' });
  ix++;
});
--></script>

Demo (click the button several times):

Animate background position

The easiest way to animate the position of a background image with jQuery, to work across-browsers, is to use the following plugin (Written by Keith Wood - http://keith-wood.name/backgroundPos.html).
1. Copy the following code into a ".js" file (for example, with the name "jquery_backgroundpos.js").

jQuery animate backgroundPosition plugin

(function($){var g=!!$.Tween;if(g){$.Tween.propHooks['backgroundPosition']={get:function(a){return parseBackgroundPosition($(a.elem).css(a.prop))},set:setBackgroundPosition}}
else{$.fx.step['backgroundPosition']=setBackgroundPosition};
function parseBackgroundPosition(c){var d=(c||'').split(/ /);var e={center:'50%',left:'0%',right:'100%',top:'0%',bottom:'100%'};
var f=function(a){var b=(e[d[a]]||d[a]||'50%').match(/^([+-]=)?([+-]?\d+(\.\d*)?)(.*)$/);d[a]=[b[1],parseFloat(b[2]),b[4]||'px']};if(d.length==1&&$.inArray(d[0],['top','bottom'])>-1){d[1]=d[0];d[0]='50%'}f(0);f(1);return d}
function setBackgroundPosition(a){if(!a.set){initBackgroundPosition(a)}$(a.elem).css('background-position',((a.pos*(a.end[0][1]-a.start[0][1])+a.start[0][1])+a.end[0][2])+' '+((a.pos*(a.end[1][1]-a.start[1][1])+a.start[1][1])+a.end[1][2]))}
function initBackgroundPosition(a){a.start=parseBackgroundPosition($(a.elem).css('backgroundPosition'));a.end=parseBackgroundPosition(a.end);for(var i=0;i<a.end.length;i++){if(a.end[i][0]){a.end[i][1]=a.start[i][1]+(a.end[i][0]=='-='?-1:+1)*a.end[i][1]}}a.set=true}})(jQuery);

2. Include the plugin in your HTML document, after the jQuery library.
<script src="jquery.js" type="text/javascript"></script>
<script type="text/javascript" src="jquery_backgroundpos.js"></script>

3. Invoke the animation on your elements, using this syntax:
$(selector).animate({ backgroundPosition: 'Xval Yval' }, speed);
- The Xval and Yval represent the horizontal and vertical offsets for the background. These may be absolute values (e.g. -100px or 50px), percentages (e.g. -25% or 50%), relative values (e.g. -=200px or +=20%), or named positions (top, left, right, or bottom).
If the vertical offset is omitted it defaults to '50%'.
If no units are specified 'px' is assumed.
- "speed" - is optional, and sets the animation speed ("fast", "slow", or milliseconds).

Code example:

$(selector).animate({backgroundPosition: '-120px 0'}, 1500); 
$(selector).animate({backgroundPosition: '30% -15%'}, 'fast');
$(selector).animate({backgroundPosition: '+=100px -=80px'}, 'slow', 'linear'); 
$(selector).animate({backgroundPosition: 'left bottom'});

Examples Animate background position

1. When click on a button, animate the background image from top-left to right-bottom.
<style type="text/css">
#idex4 {
 width:320px;
 height:80px;
 background:url('image.jpg') 0 0 no-repeat;
 border:1px solid blue;
}
</style>
<div id="idex4"></div>
<button id="bex4">Click</button>
<script type="text/javascript"><!--
$('#bex4').click(function(){
  $('#idex4').animate({backgroundPosition: '100% 100%'}, 1500);
});
--></script>

Demo:

2. Alternate the background position, horizontally right and left, with animation effect. Displays a counter with the number of clicks:
<style type="text/css"><!--
#idex5 {
 background: url('image.jpg') 0 center no-repeat;
 width:400px;
 height:80px;
 border:1px dashed green;
}
--></style>
<div id="idex5"></div>
<button id="bex5">Click</button>
<script type="text/javascript"><!--
// https://coursesweb.net
var vx = 1;
var nrclicks = 0;        // store the number of clicks
$('#bex5').click(function() {
  $('#idex5').animate({
    backgroundPosition: (100 * (vx % 2)) +'% 50%' }, 'slow', 'linear',
    // function in animate() to increment and displays the number of clicks
    function(){
      nrclicks++;
      $('#idex5').html('<h4>'+ nrclicks+ '</h4>')
    }
  );
  vx++;
});
--></script>

Demo (click the button several times):

Getting background position

To get the background position, you can use the following function.
// Returns object with values for background-position - http://snipplr.com/view/50791/
function getBackgroundPos(obj) {
  var pos = obj.css('background-position');
  if (pos == 'undefined' || pos == null) {
    // for IE, because it doesn`t know background-position
    pos = [obj.css('background-position-x'),obj.css('background-position-y')];
  }
  else {
    pos = pos.split(' ');
  }
  return {
    x: parseFloat(pos[0]),
    xUnit: pos[0].replace(/[0-9-.]/g, ''),
    y: parseFloat(pos[1]),
    yUnit: pos[1].replace(/[0-9-.]/g, '')
  };
}
This function returns an object with four properties:
      - x - the numeric value of the horizontal position (in IE is converted in pixels).
      - xUnit - the measurement unit of the "x" value (in IE is 'px').
      - y - the numeric value of the vertical position (in IE is converted in pixels).
      - yUnit - the measurement unit of the "y" value (in IE is 'px').

• Using getBackgroundPos() function:
var bgpos = getBackgroundPos($('#id'));
  // bgpos.x
  // bgpos.xUnit
  // bgpos.y
  // bgpos.yUnit

Example:
<style type="text/css">
#idex6 {
 width:320px;
 height:80px;
 background:url('image.jpg') 50% 15% no-repeat;
 border:2px dotted green;
}
</style>
<div id="idex6"></div>
<button id="bex6">Get backgroundPosition</button>
<script type="text/javascript"><!--
// function to get background position
function getBackgroundPos(obj) {
  var pos = obj.css('background-position');
  if (pos == 'undefined' || pos == null) {
    // for IE, because it doesn`t know background-position
    pos = [obj.css('background-position-x'),obj.css('background-position-y')];
  }
  else {
    pos = pos.split(' ');
  }
  return {
    x: parseFloat(pos[0]),
    xUnit: pos[0].replace(/[0-9-.]/g, ''),
    y: parseFloat(pos[1]),
    yUnit: pos[1].replace(/[0-9-.]/g, '')
  };
}

// when click on #bex6
$('#bex6').click(function(){
  // gets the object with x/y background-position
  var bgpos = getBackgroundPos($('#idex6'));
  var Xval = bgpos.x + bgpos.xUnit;     // horizontal position
  var Yval = bgpos.y + bgpos.yUnit;     // vertical position

  alert('backgroundPosition: "'+ Xval+ ' '+ Yval+ '"');
});
--></script>

Demo:

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which tag is a block element?
<div> <img> <span>
<div>Web Programming and Development</div>
Which CSS code displays the text underlined?
font-style: italic; text-decoration: underline; font-weight: 500;
h2 {
  text-decoration: underline;
}
Click on the JavaScript function that can access other function after a specified time.
insertBefore() setTimeout() querySelector()
function someFunction() { alert("CoursesWeb.net"); }
setTimeout("someFunction()", 2000);
Click on the instruction that returns the number of items of a multidimensional array in PHP.
count($array) count($array, 1) strlen()
$food =["fruits" =>["banana", "apple"), "veggie" =>["collard", "pea"));
$nr_food = count($food, 1);
echo $nr_food;       // 6
jQuery background position

Last accessed pages

  1. ActionScript 3 - Change MovieClip Color (8944)
  2. Get Mime Type of file or string content in PHP (6078)
  3. Add Text in Canvas from Input text field, as it is Typed (9807)
  4. Remove / Get duplicate array values - Reset array keys in PHP (13047)
  5. Integer and Float value in Select with PDO from string to numeric (8576)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (327)
  2. Read Excel file data in PHP - PhpExcelReader (122)
  3. The Four Agreements (97)
  4. PHP Unzipper - Extract Zip, Rar Archives (94)
  5. The Mastery of Love (87)
Chat
Chat or leave a message for the other users
Full screenInchide