Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript jQuery Basics (2014) Creating a Simple Lightbox Perfect

CSS for Jquery created elements

What would the best practice be for adding css to elements created by Jquery?

If adding elements to the .html file that are only used when javascript is enabled is not a best practice, should adding their css properties to the .css file be discouraged?

Using .css() in Jquery seems like a good option.

For example:

var $overlay = $('<div id="overlay"></div>').css({
    'background': 'rgba(0, 0, 0, 0.7)',
    'height': '100%',
    'width': '100%',
    'position': 'absolute',
    'top': '0',
    'left': '0',
    'display': 'none',
    'text-align': 'center'
});
var $image = $('<img>').css({
    'margin-top': '10%'
});
var $caption = $('<p></p>').css({
    'color': '#fff'
});

1 Answer

In this case I believe the best practice would be that the styles should be placed in a css file with a selector of #overlay.

If you have many lines of styles that depend on elements created through js and are really concerned about the file size of you css you could use js to create a link to a js.css file (named however you like)

You can see some examples of creating a link through js here: http://stackoverflow.com/questions/574944/how-to-load-up-css-files-using-javascript Though you probably don't need to do this.

Thanks for the quick response! I get what you're saying. Keep code and style seperate, and when necessary include a secondary .css with jQuery or JavaScript.