Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
163
rated 0 times [  167] [ 4]  / answers: 1 / hits: 21448  / 12 Years ago, thu, january 3, 2013, 12:00:00

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:





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



Thank you all for your precious help.


More From » jquery

 Answers
68

Honestly, the best way may be neither. If I had to pick one, the jquery css method would be my choice, just because it's cleaner, however, consider this alternative for better performance and cleaner looking code:



Create CSS classes to append to your elements when needed. For example:



.formElementAlpha {  
width:240px;
padding:4px 0;
}
.formElementBravo {
width:400px;
height:50px;
padding:20px 0;
line-height:50px;
font-size:30px;
}


then, with jquery, when you need it:



$('.formElement').addClass('formElementAlpha');


or



$('.formElement[name=bigUsernameInput]').addClass('formElementBravo');


I would reserver the jQuery css method for instances where you need to modify a specific element based on some sort of user interaction or other dynamic event that requires you to use the value of your JavaScript variables to determine the styles you are applying. Since it looks like you already know how you want to style them, let CSS do the work.


[#81113] Tuesday, January 1, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
destiney

Total Points: 175
Total Questions: 96
Total Answers: 93

Location: Zambia
Member since Sat, Nov 6, 2021
3 Years ago
;