Jump to content


Retrieving GSAP current value of css property

Recommended Posts

Hey guys.

I'm doing a simple tween on a score bar which tweens the width of a div from 0% to 0-100% depending on the users score in a game.

I want to play a sound when the bar animates and passes various points.


I'm struggling to get the % value back out of my tween instance during the onUpdate callback.


tween.target is an array containing my div.


I can call:

onUpdate: function() {
    # get a numeric percentage value 
    val = parseFloat(this.target[0].style.width)
    if(val > 0 && !played_one) {
       played_one = true;
    } else if(val > 50&& !played_two) {
       played_two = true;
    } else if(val > 90 && !played_three) {
       played_three = true;

This solution isn't the most elegant I know.


But something really doesn't feel right about "this.target[0].style.width"

I'm not 100% that this is going to give me the current percentage value correctly in all browsers.

I thought there might be a GSAP to give me this value reliably.

Link to comment
Share on other sites

Why don't you feel that value will be accurate? It is the correct way to read style values in javascript.

this   // the tween
target // whatever was passed as the animation target e.g. if it a jQuery object was used that will be returned
[0]    // first element in the jQuery object
style  // javascript object for element styles
width  // the value of the style you want

GSAP does add a _gsTransform property to DOM elements it is tweening if transforms are used so that the transform values don't need to be manually extracted from a matrix. For all other values the style property is used. If you're using something like jQuery etc you could use their methods to access values if you prefer e.g. $(foo).css('width'), but the style property is also fine. The only values that can be wonky to extract from the style property are vendor prefixed styles.

  • Like 3
Link to comment
Share on other sites

Hi Rob  :)


try this :


Edit : oops...i didnt see jamiejefferson answer :P he's right .

Link to comment
Share on other sites

Cool thanks guys.

I did try $(target).css('width') but that always returns a px value. 

I recall that element.style.width will not always return the value exactly as it was set in IE. However I've just tried it and it seems OK.


So I'll stick with using the style object then.

Thanks for your input guys.

Link to comment
Share on other sites

Thanks Carl, I saw that after I posted mine. Sorry for the duplication.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.