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

Is it better to set the styling of a page in javascript insted of css??

I meant, with css some browser don't support a few styling, so if i style it in javascript will it be compatible without the use of webkit, moz and so...??

1 Answer

Can you give an example of how you would style something in javascript?

Generally speaking, I would say it is inadvisable to style anything using javascript. Javascript is significantly more costly to run than CSS as far as performance goes. Also, having styling information in your javascript would break the principle of "separation of concerns". Finally, javascript has its own compatibility issues between browsers so you wouldn't exactly be solving the problem you're setting out to solve.

var myDiv = document.getElementById('myDiv'); var header = document.getElementById('header'); var footer = document.getElementById('footer');

// header header.style.width = "60%"; header.style.margin = "0px auto 0"; header.style.background = "lightgreen" header.style.color = "tomato";

// section
myDiv.style.background = "#FF9933"; myDiv.style.color = "white"; myDiv.style.width = "60%"; myDiv.style.margin = "0 auto 0";

// footer footer.style.width = "60%"; footer.style.margin = "0px auto 0"; footer.style.background = "lightgrey" footer.style.color = "royalblue";

Yeah, that is exactly the sort of thing you do not want to do.

what if i want to provide the client with different options so he can style the page as he likes, for that section itself ?? would it still be not a good idea ??

It would never be a good idea to use javascript to style a page in this way.

If you wanted to give the client a way of styling the page as he likes, you would probably want to use some kind of backend solution like WordPress, Rails or PHP.

Javascript should be used to create behaviors while CSS should be used to create looks. For example, you would use CSS to make a button red. You might use Javascript to make the button turn blue after the user presses it.

thanks, i had php in mind at first, but then i thought using js would be better, anyways very helpful sir :)