It seems almost the entire world has switched to using jQuery, and for good reason too! Here are some simple but helpful plugins and snippets I've written recently.
jQuery.fn.otherwise
jQuery first-timers always seem to be asking "How can I check if my selection didn't match anything?", to which the common answer is "just check the .length property". Try the following for a chainable solution instead.
Usage Example
$('button').click(function(){
$('#msg p:first')
.remove()
.otherwise(function(){
$('#msg').html('There are no more paragraphs to remove!');
});
});
type="button">Click me!>
id="msg">
>This is the first paragraph.>
>This is the second paragraph.>
>This is the third paragraph.>
>
See it in action!
Plugin Code
jQuery.fn.otherwise = function(func) {
if (!this.length) {
func.apply(this);
}
return this;
};
jQuery.fn.followLink
This was my first attempt at a jQuery plugin. I wanted to simulate a link being clicked, however .click() only triggers jQuery click handlers and doesn't change the current page.
Usage Example
// navigate prev/next depending on left/right arrows pressed
$(document).keydown(function(e){
if (e.which == 37) {
$('#prev').followLink();
} else if (e.which == 39) {
$('#next').followLink();
}
});
href="prev.html" id="prev">Go to the previous page> />
href="next.html" id="next">Go to the next page>
See it in action!
Plugin Code
jQuery.fn.followLink = function(){
this.attr('href', function(){
window.location = this.href;
});
};
jQuery.fromXMLString
Ever had a string of XML that you'd love to use jQuery on? Although you can pass an XML string to jQuery in Firefox without additional code, it doesn't work in IE7. Try this baby instead!
Usage Example
var strXML = 'TrentPunchy';
$('#location').text(
$.fromXMLString(strXML).find("person[id='69'] location").text()
);
>Trent is from id="location">>.>
See it in action!
Plugin Code
jQuery.fromXMLString = function(strXML){
if (window.DOMParser) {
return jQuery(new DOMParser().parseFromString(strXML, "text/xml"));
} else if (window.ActiveXObject) {
var doc = new ActiveXObject("Microsoft.XMLDOM");
doc.async = "false";
doc.loadXML(strXML);
return jQuery(doc);
} else {
return jQuery(strXML);
}
};
Open external website links in a new window
Want all links away from your site to open in a new window? Although this is not as "jQuery-like" as the previous examples, it's fast and gets the job done.
It only modifies links that don't have a "target" attribute already set. I also like to make all pdfs open in a new window.
$(function(){
$('A, AREA').filter(function(){
return (!this.target && (this.href.indexOf(window.location.hostname) == -1 || this.href.match(/\.pdf$/i)));
}).attr('target', '_blank');
});
See it in action!