Jump to content

Search In
  • More options...
Find results that contain...
Find results in...

Convert css string to object

Warning: Please note

This thread was started before GSAP 3 was released. Some information, especially the syntax, may be out of date for GSAP 3. Please see the GSAP 3 migration guide and release notes for more information about how to update the code to GSAP 3's syntax. 

Recommended Posts

Hey guys,


I have a dynamic template, where you can input css into the XML feed, and the banner will read that on run time and adjust the banner overwrite the styles using set:

 TweenMax.set(element, newValuesObject);

And I've managed to cobble together bits of string replaces and RegEx:

var myDynamicCSS = "color:#ffffff; background-color: #00ffbb; text-align: left; border: 1px solid green";

String.prototype.toCamelCase = function() {
  return this.replace(/^([A-Z])|[\s-](\w)/g, function(match, p1, p2, offset) {
    if (p2) return p2.toUpperCase();
    return p1.toLowerCase();

const convertCSS2JS = (css) => {
  let frameCSS = css.replace(/([\w-.]+)\s*[^;]+);?/g, '$1:$2,');
  frameCSS = frameCSS.replace(/,+$/, '');
  let properties = frameCSS.split(', ');
  let frameCSSObj = {};
  properties.forEach(function(property) {
      let cssProp = property.split(':');
      let cssKey = cssProp[0].toCamelCase();
      let cssValue = cssProp[1].trim();
      frameCSSObj[cssKey] = cssValue;
  return frameCSSObj

TweenMax.set(myDynamicElement, convertCSS2JS(myDynamicCSS]));

But I'm unsure of how easily breakable this is?




See the Pen GZVedX by joemidi (@joemidi) on CodePen

  • Like 2
Link to comment
Share on other sites

What do you mean by breakable? See if we can come up with combinations of CSS stings to see if this fails?

  • Like 1
Link to comment
Share on other sites

Yea lets break it!!


I'm off to the pub.

Link to comment
Share on other sites

Ok, let's resort to violence and see what we can break. 




Pub on a Tuesday? Man.... I've already used my lunch allowance, can't come stalk you but, give me a heads up sometime and I might show up (I'm around London Bridge this and next week).

Link to comment
Share on other sites

very nice, handled multiple transforms nicely and they got converted to a matrix by set()

var myDynamicCSS = "color:#ffffff; background-color: #00ffbb; border-radius:20px; transform:translateY(100px) rotate(30deg) scaleX(0.5)";
  • Like 1
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.