Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to add new css rules with jquery?

I am dynamically inserting some html on a web page (after I detect an event from the user). This html needs some css styling and I am wondering what is the cleanest way to do it, using jQuery. I am not the website developer, so I can't add those rules to the original css.

Assume I have already inserted some html without styling, including a formElement class. I can write in my document a new <style> block, for instance:

my_html =  '<style type="text/css">';
my_html += '   .formElement {';
my_html += '       display: block;';
my_html += '       width: 240px;';
my_html += '       position: relative;';
my_html += '       padding: 4px 0;';
my_html += '   }';
my_html += '</style>';
my_html = $(my_html);
$('body').prepend(my_html);

Or, I can use the css method:

$('.formElement').css({
    'display': 'block',
    'width': '240px',
    'position': 'relative',
    'padding': '4px 0'
});

Which solution is the best/cleanest?

EDIT:

As I can't directly add the rules in the CSS, I will stick with the css method of jQuery. Some other related questions provide solutions as well:

  • Create a CSS rule / class with jQuery at runtime
  • Changing CSS Rules using JavaScript or jQuery

I can't really use jQuery plugins, but if I could, I would certainly use jQuery.Rule

Thank you all for your precious help.

like image 385
clement g Avatar asked Jan 03 '13 09:01

clement g


2 Answers

Don't mix css and js together, especially if your properties don't contain computed or dynamic values: just define a CSS class

.mystyle {
    display: block;
    width: 240px;
    position: relative;
    padding: 4px 0;
}

and set the class

$('.formElement').addClass('mystyle');
like image 99
Fabrizio Calderan Avatar answered Oct 13 '22 01:10

Fabrizio Calderan


This:

$('.formElement').css({
        'display': 'block',
        'width': '240px',
        'position': 'relative',
        'padding': '4px 0'
    });
like image 22
Klevis Miho Avatar answered Oct 13 '22 01:10

Klevis Miho