It’s kind of redundant to post a “Get Firefox!” banner to someone already using Firefox, but it’s useful to show them an upgrade banner if they’re on an old version. It’s also useful to show Firefox users a banner for Spread Firefox.
This can be done easily with PHP or other server-side scripting languages, but sometimes you have to use static HTML files. That’s where client-side scripting becomes necessary. Last month I posted some sample code that used document.write, which doesn’t work with XHTML. (On top of that, the <noscript>
blocks I used ended up causing validation errors because of their location!)
I’ve redone everything with DOM scripting, which will work with either HTML 4 or XHTML 1.0.
1. Put the following in a file called sfxlinks.js:
function replaceFirefoxLink(linkID) {
if(linkNode=document.getElementById(linkID)) {
var newLink=document.createElement('a');
var newImg=document.createElement('img');
var change=0;
if ( 0 <= navigator.userAgent.indexOf('Firefox/0') ||
0 <= navigator.userAgent.indexOf('Firefox/1.0') ) {
change=1;
newLink.setAttribute('href','YOUR_UPGRADE_LINK');
newImg.setAttribute('alt','Upgrade to Firefox 1.5!');
newImg.setAttribute('title','Upgrade to Firefox 1.5!');
newImg.setAttribute('src','PATH_TO_BANNER');
} else if (0 <= navigator.userAgent.indexOf('Firefox')) {
change=1;
newLink.setAttribute('href','YOUR_REFERRAL_LINK');
newImg.setAttribute('alt','Spread Firefox!');
newImg.setAttribute('title','Spread Firefox!');
newImg.setAttribute('src','PATH_TO_BANNER');
}
if(change) {
newLink.appendChild(newImg);
var parentNode=linkNode.parentNode;
parentNode.replaceChild(newLink,linkNode);
}
}
}
2. Use your regular Spread Firefox affiliate link and add a unique ID — let’s use id="FxLink"
as an example — to the <a> tag.
3. Load the script in your document’s <head> section:
<script type="text/javascript" src="sfxlinks.js">
4. Call the function in the body onload event using the ID you chose in step 2:
<body onload="replaceFirefoxLink('FxLink')">
When the page loads, the script will check the visitor’s browser to see if it’s an old version of Firefox or a current version of Firefox. If it’s an old version, it’ll replace your standard button with your upgrade button. If it’s a current version, it’ll replace it with a Spread Firefox button with your referral link. Otherwise, it leaves the button alone.
This has a lot of advantages over the old version, including XHTML compatibility, no need for <noscript>
blocks, easier validation, and it still degrades gracefully (if JS is unavailable or old, it leaves your normal button in place).
You can see it in action on my website, Flash: Those Who Ride the Lightning.
Originally posted on my Spread Firefox blog.