Useful wee jQuery snippets
Here are some short jQuery snippets I use on a regular basis:
Header catch-all snippet
$('h1,h2,h3,h4,h5,h6').addClass('hx');
This snippet adds the class .hx to all heading elements. Having this class to use comes in handy for non-essential styling and saves you from typing out the following #content h1, #content h2, #content h3… etc. Ideally I’d have a h* class but CSS isn’t a fan of the asterisk.
Strict doctype friendly new window snippet
$('a[rel=external]').click(function(){
window.open(this.href);
return false;
});
Sometimes you just have to open a link in a new window/tab and this is an old but still very useful snippet to have.
Note: If you don’t agree with the use of rel attribute for defining external links simply swap rel out for class or even a[href^"=http://"] which would target all links starting with http://.
Print this page snippet
$('<a href="#print">Print this page</a>').click(function(){window.print();}).appendTo("body");
Appends a link to the body allowing the user to print out the page. You can change body to any other element in the document. You can also change .appendTo to .prependTo or one of the many other jQuery manipulation thingamabobs.
Grab cite and stick it into a title attribute snippet
$("q, blockquote").hover(function(){
var getCite = $(this).attr("cite");
var cite = ('Cite — ' + getCite);
$(this).attr({ title: cite });
});
Now this one probably isn’t all that useful to everyone but I thought I’d stick it in anyway. I have no doubt it could be improved so if you have a suggestion please post it. What it does is grab the cite attribute content (usually a URL) and sticks it into a title attribute so you can hover over the element and see the citation.
Got any of your own to share?
It would be great to share common snippets you find useful in every day use, so please feel free to suggest any in a comment and maybe you could make this post even better :)