1 minute read
A very smart designer who I respect a lot asked me a question today via IM that I thought would make a good post.
…so I know jquery is great for doing things with CSS – but I think of only using it when I can’t actually get to the tag or it needs to be changed on a particular event – but do you think it is better to make CSS changes in jquery vs CSS – what are the pros and cons here.
Here’s my thinking about this. I would always err on the side of CSS if possible. jQuery should be used to change CSS based upon some sort of user-generated event.
Many people seem to use jQuery to make CSS changes on page load (in a $(document).ready()) when they have trouble getting the CSS selectors right. If the selector is hard to get right in CSS, then it’ll probably be pretty hard in jQuery as well because the jQuery selector syntax is roughly the same as CSS3 selectors. jQuery gives you the ability to traverse the DOM, of course, so it can be easier to find an “anchor element” from which to navigate to the element you want to style.
My mantra is something like:
Ask the server to paint the page. Use jQuery to give it behaviors and interactivity.
Setting CSS with script on page load violates this in that it’s doing part of that initial painting. There’s also going to be at least a small delay until the script loads which can make the page load look “funny” (technical term).
You’ll see a lot of blog posts that show setting CSS on page load with jQuery, but think carefully in each case about whether it makes sense. If you’re doing it just to get around figuring out the right selectors in your CSS, then think again.
I’ll admit that sometimes I cheat on this, especially if I happen to have a .js file open instead of a CSS file. But I also try to make a pass back through my scripts to move things into the CSS that ought to have been there in the first place. You should too!