2

I have the following JS code that changes the width depending on value of the data-percentage HTML attribute:

var addRule = (function (sheet) {
  if(!sheet) return;
  return function (selector, styles) {
    if (sheet.insertRule) return sheet.insertRule(selector + " {" + styles + "}", sheet.cssRules.length);
    if (sheet.addRule) return sheet.addRule(selector, styles);
  }
}(document.styleSheets[document.styleSheets.length - 1]));

var i = 101;
while (i--) {
  addRule("[data-percentage='" + i + "%']", "width:" + i + "%");
}

See the demo: http://jsfiddle.net/YYF35/

Instead of width, for some elements I want to change their height.

How can I change the code so that depending on class of the div I change the height or width of element (depending on the data-percentage attribute number of course)?

I don’t want to create a different HTML attribute for it, like so:

while (i--) {
  addRule("[data-percentage-width='" + i + "%']", "width:" + i + "%");
  addRule("[data-percentage-height='" + i + "%']", "height:" + i + "%");
}

jQuery can be used as well. Any ideas?

1
  • Do you really need to modify the stylesheet, or could you just change the elements? For that matter, why not just hardcode 100 rules into the stylesheet? (Well, 200 rules if you want separate width and height.) div[data-percentage-height=1].change-height { height: 1% } and such? Commented Nov 22, 2013 at 7:44

2 Answers 2

4

Your code is adding rules. If you really want to be doing that, just add more rules:

var i = 101;
while (i--) {
  addRule("[data-percentage='" + i + "%'].change-width", "width:" + i + "%");
  addRule("[data-percentage='" + i + "%'].change-height", "height:" + i + "%");
}

Now, elements with the change-width class will have their width modified, and elements with the change-height class will have their height modified (and you can use both if you like).

Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

$("div[data-percentage]").each(function(){

    $(this).css({
        width: $(this).attr('data-percentage')
        //height: $(this).attr('data-percentage')
    });
});

http://jsfiddle.net/YYF35/1/

1 Comment

Look at the code again. It's building a stylesheet, not changing the elements themselves.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.