traviblog

just some sort of lame blog

I $("♥") jQuery

I got a bunch of typography guidelines for a site from one of our designers today which contained the following rule:

First line of paragraph gets a 10 pixel indent (except for first paragraph on page and paragraph following a subhead)

I hate disappointing our designers with technical hurdles so I though that I'd give it a shot. Since the adjacent sibling selectors and :first-child pseudo-class aren't supported well by many browsers, *COUGH*IE6*COUGH* I let out a sigh and started adding class="first" on all the first paragraphs in the HTML example templates I was testing with. I thought: there has GOT to be a better way to do this with jQuery. I can't imagine what it would take to dynamically add those classes in the CMS we're making for this site anyways. I had this CSS:

#content p
{
	text-indent: 10px;
}

I then added this JS:

$(document).ready(function()
	{
		// reset h1+p, h2+p, h3+p, p:first-child
		$("#content h1+p, #content h2+p, #content h3+p, #content p:first-child").each(function (i) 
			{
				$(this).css("text-indent", "0");
			}
		);
	}
);

...and voila! It works like a charm! Now instead of massacring markup with needless (and painful to add on the fly) classes, I can just do the crazy stuff with jQuery.

Update: John pointed out that my JS can be even shorter:

$(document).ready(function()
	{
		// reset h1+p, h2+p, h3+p, p:first-child
		$("#content").find("h1+p, h2+p, h3+p, p:first-child").css("text-indent", "0");
	}
);
Comments

Archived Comments

namedatecomment
Adam Lindsay That is cool, of course, it shouldn't have to be done this way. Especially considering you are now poorly mixing layers, that could easily be missed in the future. Some future maintainer of the site will be wonder and saying "I can't figure out what these paragraphs don't indent, when clearly the CSS says 10px".

Anyways, good code, I have been meaning too check out JQuery, just Prototype/Scriptalicous is so entrenched in Rails, I have had little reason to look at other libraries.
John Resig Glad you're having fun with it :-)

Just to make your code a little bit shorter:
$("#content").find("h1+p,h2+p,h3+p,p:first-child").css("text-indent",0);

Keep up the great work!

@Adam: You should definitely check out jQuery... it's written by some cool people - ha!
travis Oh I definitely agree that this is very hackish. But I can't force IE to work correctly and I certainly can't force people to upgrade (as much as I'd like to). Plus I won't have to wait for CSS3 to come out of draft and for browsers to implement its features (as far as the new advanced selectors go).

For other programmers blessed/cursed with maintaining my code, that's what /*comments*/ are for. ;-)

Definitely check out jQuery though. It's so damn useful. If only for the $(document).ready() and the $() in general.
travis Sweet! Thanks John!

comments powered by Disqus