0

How do I use JQuery's animate() on the background size of a div if I were to change either the width or the height, but not both.

For example, if I wanted to change the width, would something like the following work?

$("#buttonPic").animate({
    backgroundSizeW: "-=20px",
});

I could not find a similar question to this on SO

buydadip
  • 8,890
  • 22
  • 79
  • 154

4 Answers4

1

I have doubts about backgroundSizeW property, seems a bit invalid to me:

$("#buttonPic").animate({
    backgroundSize: "-=20px auto"  // <-----it should work
});
Jai
  • 74,255
  • 12
  • 74
  • 103
  • yep it does work, but I was wondering if I can change only width not width and height. Something similar to this is possible with `background-position`, one can do `backgroundPositionX` with animate and it works – buydadip Jan 18 '16 at 08:02
  • @Bolboa why don't you set that `auto` explicitly. – Jai Jan 18 '16 at 08:09
0

The .animate() function can be used as follows

$( "#go" ).click(function() {
  $( "#block" ).animate({
    width: "200px",
    }, 1500 );
});
div {
    background-color: #bca;
    width: 100px;
    border: 1px solid green;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<button id="go">&raquo; Run</button>
<div id="block">Hello!</div>
Tushar Gupta
  • 15,504
  • 1
  • 29
  • 47
  • This will not work, I want to change only the width of the background image for my div, not the div itself...Currently the divs background-size is set to `60px 60px` – buydadip Jan 18 '16 at 07:41
0

You can animate() background width height with background-size

$( "#buttonPic" ).click(function() {
  $( "#divBlock" ).animate({
    "background-size": "-=20px",
    }, 1500 );
});
Parth Trivedi
  • 3,802
  • 1
  • 20
  • 40
  • I did not down vote, but this will work only if I want to change both width and height of `background-size`, currently it is set to `background-size: 60px 60px`, I want to change only one of these attributes, not both – buydadip Jan 18 '16 at 07:44
  • Can you write html also? you should check http://www.w3schools.com/cssref/css3_pr_background-size.asp – Parth Trivedi Jan 18 '16 at 07:48
  • I don't see why it would be necessary, but here... `` – buydadip Jan 18 '16 at 07:51
  • `background-size` works with `width` and `height` if you give it both. get one with jquery and set both. – Parth Trivedi Jan 18 '16 at 07:53
  • You should check this http://stackoverflow.com/questions/5106243/how-do-i-get-background-image-size-in-jquery?answertab=active#tab-top – Parth Trivedi Jan 18 '16 at 07:58
0

Maybe,You can change the idea,for example:

$("#buttonPic").animate({
    backgroundSize: "40px 60px",
});

if you want the 'width' is a 'variable',you can set a width to istead the fixed value;just:

var wid=60;
wid-=20;
Anan
  • 328
  • 2
  • 14