0

I am working on a code base and am using JQuery to add DOM elements.I want to know if it is considered better practice to style them with JQuery or just create them with JQuery then go to the style sheet and add new CSS blocks to style them.

Thank you.

1
  • Unfortunately, questions related to programming are considered off-topic for this site. You might ask this question over at Stack Overflow, but be sure to search the answers there and read their FAQ first. Please feel free to ask other questions that fall under this site's guidelines in the future. – dan Jan 27 '14 at 1:14
3

In my very personal opinion, it depends much of your project. But, in general, a new CSS block is usually better accepted as better practice. When you style your DOM elements using js the maintenance can become very difficult to maintain. Personaly, I like to use js to edit the class attribute, instead styling directly the element. Example:

Instead of:

$('test').setStyle({
    opacity: 1,
    transition: 'all 3s'
});

//that becomes
<div id="teste" style="display:none; opacity: 0; " >...</div>

I rather prefer the following approach:

$('teste').addClass('visible');

<style type="text/css" >
.visible {
    opacity: 1;
    transition: all 3s;
}
</style>

//that becomes
<div id="teste" class="visible" >...</div>

I made a very rudimentar fiddle to illustrate it: http://jsfiddle.net/Vtra8/1/

In my view, it is a lot easier to understand, to maintain e to debug your code specially when working on collaborative projects.

Not the answer you're looking for? Browse other questions tagged or ask your own question.