0

I know that jQuery cannot directly manipulate CSS pseudo elements, and I've already read a bunch of posts here that don't answer my question.

I need to modify the CSS of a pseudo element with the value of a field.

My project has an icon displayed before text using :before. I need that icon's font-size to dynamically change as the user changes the value in a field.

I have the basics of the script down, but I just can't get it to change the font size with each change. For example (#base_size is the field with the integer value, a:before is the pseudo element that has inserted the icon):

$('#base_size').change(function() {
    var baseSize = $(this).attr('value');
    document.styleSheets[0].insertRule('.item a:before { font-size:' + baseSize + 'px !important; }');
});

This particular jQuery will change the font size, but only the first time. Further changes in #base_size don't affect the pseudo element, but each change does create a new CSS rule. Oddly, Chrome dev tools shows ".item a::before" (one for each change) with two colons and no declarations.

I'm probably going about this all the wrong way. I will be very grateful for any help!

  • In CSS3, The single colon is reserved for pseudo classes, like `:active` and `:visited`. Double-colon is intended for psuedo elements like `::before` and `::after`. CSS2 used a single colon for both. – mwcz Jul 15 '13 at 15:09
  • Why are you inserting rules add your stylesheet instead of using inline styles? – Pieter Jul 15 '13 at 15:10
  • possible duplicate of [Manipulating CSS pseudo-elements using jQuery (e.g. :before and :after)](http://stackoverflow.com/questions/5041494/manipulating-css-pseudo-elements-using-jquery-e-g-before-and-after) – Blazemonger Feb 03 '14 at 20:10

1 Answers1

-1

Why futz with stylesheets?

Try changing the CSS instead:

$('#base_size').change(function() {
    var baseSize = this.value;
    $('.item a:before').css({ 'font-size': baseSize + 'px' });
});
Naftali
  • 144,921
  • 39
  • 244
  • 303