Tag: javascript

Optimizing Google Analytics Performance

Posted on February 4, 2008 in Optimization by Jeff Starr

[ Image: Global Map Icon ] It has occurred to me lately that I no longer use Google Analytics for Perishable Press. Instead, I find myself keeping an eye on things using Mint almost exclusively. So, the question now is: do I continue serving the GA JavaScript to keep the profile active just in case I ever need the additional stats? I mean, Mint already does a great job at recording all of information I could ever need, so I no longer see the use for Google Analytics. I do wonder, however, if Google ranks GA-enabled sites a bit higher than non-GA sites. Hmmm.. it seems to me that there are several options going forward..

Option 1: Continue with Google Analytics

The easiest thing for me to do at this point would be to just leave it alone: continue serving the extra 6.3K/21.4K GA JavaScript (i.e., urchin.js) to site visitors. Sure, I may never actually use the volumes of data I am collecting via Analytics, but hey, who cares, right? Of course, delivering the urchin.js file requires bandwidth and other server resources, and also tends to slow things down a bit, especially on those rare occasions when the Google server bogs down.

Continue Reading

Quick JavaScript Tip: Auto-Highlight Form Inputs and Textareas

Posted on December 10, 2007 in Function by Jeff Starr

I realize that probably everybody already knows this elementary and absolutely dead-simple JavaScript tip, but I was surfing around the other day and encountered a page that made great use of some auto-highlighted textarea content. The idea is simple, include a snippet of JavaScript to enable users to automatically highlight/select upon focus any chunk of text located within a form input or textarea element. I would imagine this trick works with just about any element — buttons, links, you name it. With the following code in place, content within a textarea will be highlighted/selected when the user hovers over or focuses the area. And for input elements, text will be highlighted if present, and, if not, a blinking cursor will appear, ready to serve. Very nice ;)

Continue Reading

Protect Your Site Against UserCash and Other Scumbags

Posted on December 3, 2007 in Websites by Jeff Starr

In this brief article I explain the atrocity that is UserCash and then provide the JavaScript needed to protect your site.

What is UserCash?

UserCash is an online advertising program that uses redirects and frames to exploit your site with advertisements. UserCash customers link to target sites using rewritten URL’s generated via the UserCash “generator/compiler.” There are two types of these rewritten UserCash links:

  • Links that use frames to create banner-like ads above your pages
  • Links that use frames to deploy landing-page ads before your pages

Continue Reading

RefreshMints: Refresh Stats Bookmarklets for Mint 2

Posted on November 27, 2007 in Websites by Jeff Starr

[ Mint Icon ] Last week, I finally got around to upgrading to Mint 2.14. The new version is quite impressive, and well worth the time (and cash) spent upgrading. In the process, however, one of my favorite, most heavily used bookmarklet things ceased to work.

Before the upgrade, I had been enjoying the highly useful Refresh-All bookmarklet by Jonathan Snook. Snook’s Mint-refresh bookmarklet made it super-easy to update all Mint data panels without having to refresh the entire page. Using the bookmarklet is much faster that reloading the browser, and there is even an alternate version that will refresh panels automatically at user-specified intervals.

Continue Reading

Open External Links as Blank Targets via Unobtrusive JavaScript

Posted on November 20, 2007 in Function by Jeff Starr

Beginning with this article, I am serving up a short series of unobtrusive JavaScript functions that I use to enhance the functionality of Perishable Press. In this post, I present a comprehensive JavaScript method of opening external links in new windows (or tabs, depending on the browser).

One way of opening links in new windows is to insert the HTML target="_blank" attribute into all necessary anchor elements (<a href=""></a>). This method works well, but generates validation errors when used with XHTML-Strict doctypes.

A better solution is to employ some unobtrusive JavaScript to progressively enhance your documents with “blank-target” functionality. Using the following code, 99% of your visitors (those with JavaScript) will enjoy external links opening in new windows, while the remaining 1% of your audience (those without JavaScript) will enjoy your site without even realizing they are missing out on those wonderful blank-targeted links. It’s a “win-win” situation ;)

Continue Reading

Prevent JavaScript Elements from Breaking Page Layout when Following Yahoo Performance Tip #6: Place Scripts at the Bottom

Posted on November 12, 2007 in Presentation, Structure by Jeff Starr

By now, everyone is familiar with the Yahoo Developer Network’s 14 “best-practices” for speeding up your website. Certainly, many (if not all) of these performance optimization tips are ideal for high-traffic sites such as Yahoo or Google, but not all of them are recommended for smaller sites such as Perishable Press. Nonetheless, throughout the current site renovation project, I have attempted to implement as many of these practices as possible. At the time of this writing, I somehow have managed to score an average 77% (whoopee!) via the YSlow extension for Firebug.

Of the handful of these tips that I am able (or willing) to follow, number 6 — move scripts to the bottom — is definitely one of the easiest. The reason for doing this is at least twofold:

[…] it’s better to move scripts from the top to as low in the page as possible. One reason is to enable progressive rendering, but another is to achieve greater download parallelization.
— Yahoo! Developer Network

Many people mistakenly assume that the <script> element (and associated contents) must be located squarely in the document <head>, however, this simply isn’t true. As outlined in the official HTML 4.01 Document Type Definition and also in the official XHTML 1.1 Document Type Definition, the <script> element is allowed:

Continue Reading

The Ultimate JavaScript Library for Embedding Flash Content

Posted on July 31, 2007 in Function by Jeff Starr

[ Image: SWFfix Logo ] Earlier this year, Geoff Stearns and Bobby van der Sluis teamed up to create the “ultimate JavaScript library for embedding Flash content” into web documents. For those of you familiar with techniques for embedding Flash, these two names are instantly recognizable. Geoff Stearns is the author of SWFObject and Bobby van der Sluis is the author of UFO. Easily, SWFObject and UFO are the two best and most widely used techniques for detecting and embedding Flash content. Needless to say, when I heard that these two great minds were collaborating on an even better method to embed Flash, I was very excited to check out the fruits of their collective efforts..

On July 25th, 2007 the first publicly available version (0.2 - public alpha) of SWFFix was released to the masses. SWFFix is a Flash-embedding JavaScript library featuring standards-compliant markup, Flash-version detection, and Express-Install support. SWFFix uses the nested-objects method to optimize cross-browser support, deliver alternate content, and facilitate graceful degradation. SWFFix “fixes” the issues commonly associated with the nested-objects method (e.g., the click-to-activate requirement of IE6 and Opera 9+), providing greater functionality and a richer user experience. SWFFix also features dynamic embedding of Flash content for (X)HTML documents. Best of all, the SWFFix library consists of a single, extremely lightweight JavaScript file — only 12KB (unzipped) or 3.4KB (gzipped)! Overall, definitely impressive.

Continue Reading

Slideshow Code for Dead Letter Art

Posted on July 29, 2007 in Function, Websites by Jeff Starr

[ Icon: DLa Joker ] Pardon this post! I am posting this information online for personal references purposes. I may need to revisit this code at some point in the future, and if I post it here I will always know where to find it (trust me, it would disappear into the abyss if I tried storing it offline). So, although it is intended solely for myself, feel free to extract and use anything you like, as long as commented attribution remains. What we have here are two different methods for including a slideshow on a web page. The first method employs the techniques discussed in this article, while the second method skips the Flash and employs only the JavaScript portion of the slideshow. Here is some additional help with embedding Flash content, including slideshows, and JavaScript techniques.

Continue Reading

Another Mystery Solved..

Posted on July 25, 2007 in Function, WordPress by Jeff Starr

Recently, after researching comment links for an upcoming article, I realized that my default <input> values were being submitted as the URL for all comments left without associated website information. During the most recent site redesign, I made the mistake of doing this in comments.php:

...

<input class="input" name="url" id="url" value="[website]" onfocus="this.select();" type="text" tabindex="3" size="44" maxlength="133" alt="website" />

...

Notice the value="[website]" attribute? It seemed like a good idea at the time — I even threw in a nice onfocus auto-highlighting snippet for good measure. I ran the form with this in place for around eight weeks before finally noticing multiple comments using this for their site URL:

Continue Reading

Absolutely Fabulous Browser Bookmarklet Things

Posted on July 24, 2007 in Websites by Jeff Starr

[ Image: Fabulous Shot of Immortal's Abbath and Horgh ] ..Or something. Frankly, I just needed an excuse to post these steaming little beauties online. Please note that I don’t lay claim 1 to most of these browser bookmarklet/favelet tricks, but I do find them extremely useful. They are posted here for the sake of convenience and for reference purposes, so use at your own risk (i.e., I am not responsible if they crash your browser). Although I use most of these bad boys with Firefox, I wouldn’t be terribly surprised if they also functioned properly in other modern browsers. Nonetheless, along with each bookmarklet/favelet thing, I try to provide as much relevant information as possible, because sometimes you just feel like you’re from another planet. Happy head-scratching!

What are these things?

“Bookmarklets,” “Favelets,” “Browser Enhancement Things” — whatever you want to call them — help increase productivity and simplify tasks executed from within your browser window. Basically, these things are stored as bookmarks and perform some task — such as resize the browser window — when they are clicked. Hmm, perhaps I should check Wikipedia for the “Official” definition .. — nah.

How do I install them?

Installation of these lil’ miracles could not be easier. In most modern browsers, simply drag and drop the bookmarklet link onto your shortcut toolbar (Firefox, Safari, et al) or right-click and “Add to Favorites” (Internet Explorer). Pretty easy. There is a more complicated method as well. Create an empty bookmark or Favorite and copy & paste the bookmarklet source code into the URL field. Either way, these things are pretty common and you shouldn’t have too much trouble. So, without further ado..

Continued..

CSS Throwdown: Preload Images without JavaScript

Posted on July 22, 2007 in Presentation by Jeff Starr

Clean, easy, effective. You don’t need no stinking JavaScript to preload your images. Nope. Try some tasty CSS and (X)HTML instead! Here’s how.. (only two steps!)

Step 1 — Place this in your CSS file:

div#preloaded-images {
   position: absolute;
   overflow: hidden;
   left: -9999px; 
   top: -9999px;
   height: 1px;
   width: 1px;
}

Step 2 — Place this at the bottom of your (X)HTML document:

<div id="preloaded-images">
   <img src="http://perishablepress.com/image-01.png" width="1" height="1" alt="" />
   <img src="http://perishablepress.com/image-02.png" width="1" height="1" alt="" />
   <img src="http://perishablepress.com/image-03.png" width="1" height="1" alt="" />
</div>

..and that’s a wrap! All images are preloaded and ready for calling as you please. Completely valid, standards-compliant image preloading via CSS and (X)HTML!!

Compressed JavaScript Compression

Posted on April 24, 2007 in Function by Jeff Starr

In this article, we extrapolate our favorite CSS-compression technique for JavaScript. Below, we outline the steps required to auto-compress your JavaScript documents via gzip and PHP. Two different compression methods are presented. The first method does not require htaccess, but rather involves the manual editing of JavaScript files. The second method employs htaccess to do all the work for you, thus requiring much less effort to implement. In either case, the result is the same: automatically compressed content delivered only to supportive browsers, resulting in reduced bandwidth, faster loading times, and smiling visitors :)

Continue Reading

Embed Flash or Die Trying

Posted on April 17, 2007 in Accessibility, Function by Jeff Starr

[ Image: 50 Cent ]
Embed Flash or Die Tryin’
Web designers and developers looking to embed Flash content into a web page currently enjoy a wide variety of methods from which to choose. The most common methods vary along several key dimensions, including standards-compliance, user-friendliness, and universal support. Some methods make it easy to provide alternative content, others enable auto-activation of Flash content, while others feature plugin-detection functionality. In an attempt to round-up the myriad techniques, this article presents nine of the most useful, practical, and popular methods for embedding Flash content.

Continue Reading

Flash-Detection Triple-Threat

Posted on March 19, 2007 in Accessibility, Function by Jeff Starr

In our previous article, Alternate JavaScript Slideshow for SlideshowPro, we present an elaborate method for providing alternate content specifically for SlideshowPro. Although the method points toward a more generalized adaptation, its overall functional implementation remains focused on the presentation of slideshows.

This article explores the generalization of the previously defined method for providing alternate JavaScript content when Flash support is not detected. Using skyzyx.com’s excellent Flash-detection script, Flash Detect 3, we will outline a general approach for supporting the following browser configurations:

Browser supports the required version of Flash
Excellent. This is the ideal situation. Your Flash-based content will be displayed as intended.
Browser supports Flash, but has not upgraded to the required version
Okay. In this situation, you could serve either JavaScript content or retro-Flash content (i.e., Flash content that requires a lesser version of Flash). Detection is also provided for virtually any version of Flash, enabling delivery of multiple movie alternatives.
Browser does not support Flash, but does support JavaScript
Not bad. Non-Flash browsers will receive alternate JavaScript content. User’s won’t know what they’re missing.
Browser does not support JavaScript, but does support Flash
For Flash content that does not require JavaScript to function, the browser will display the Flash content as intended, assuming sufficient Flash version. When the version of Flash is insufficient, non-Flash users will see either retro-Flash content, animated gif content, or static image content, depending on your preference.
Browser supports neither JavaScript nor Flash
Worst case. Even so, all hope is not lost. In this situation, visitors will see either animated gif content, or static image content.

Continue Reading

Alternate JavaScript Slideshow for SlideshowPro

Posted on March 12, 2007 in Accessibility, Function by Jeff Starr

For the unenlightened, SlideshowPro (SP) is a Flash-based slideshow-authoring system that delivers full-featured, high-end, Flash-based slideshows. Websites featuring SP slideshows present content in sophisticated fashion, inspiring users with elegant captions, beautiful transitions, and intuitive navigation.

However, many visitors are unable to experience SP slideshows because they lack the requisite Flash support. SlideshowPro-based slideshows currently require Flash 7 or better to function. And, although Flash 7 is quite common, it is far from ubiquitous. In the "worst-case" scenario, Flash-challenged visitors will see a broken webpage or missing content. Unfortunately, the typical "best-case" scenario is not much better, as non-Flash users typically will see a single, static image, which is generally served via something similar to:

<object classid="clsid...">
 <param name="movie..." />
 <embed src="http://domain.tld/..." />
 ...
 <img src="http://domain.tld/path/to/alt/image.jpg" alt="alternate image served for non-Flash browsers" />
 ...
</object>

Continue Reading

Go Back via JavaScript and PHP

Posted on March 12, 2007 in Function by Jeff Starr

Use this simple code as a button that will return users to the previous page:

<form>
 <input type="button" value="Return to previous page" onClick="javascript:history.go(-1)" />
</form>

Here it is as a simple text link:

<p>
 <a href="javascript:history.go(-1)" title="Return to the previous page">&laquo; Go back</a>
</p>

You can make things easier by serving PHP and printing the link automatically. Here is the button link:

echo "<form><input type=\"button\" value=\"Return to previous page\" onClick=\"javascript:history.go(-1)\"></form>";

And here is the PHP code to print a "Go back" text link:

echo "<p><a href=\"javascript:history.go(-1)\" title=\"Return to previous page\">&laquo; Go back</a></p>";

Better yet, you can kick the accessibility factor up a notch by using PHP’s inherent HTTP_REFERER variable to write explicitly the previous URL, thereby eliminating the JavaScript requirement (thanks to Rick Beckman for the idea):

<?php $referer = $_SERVER['HTTP_REFERER'];
   if (!$referer == '') {
      echo '<p><a href="' . $referer . '" title="Return to the previous page">&laquo; Go back</a></p>';
   } else {
      echo '<p><a href="javascript:history.go(-1)" title="Return to the previous page">&laquo; Go back</a></p>';
   }
?>

The previous code will create an explicit "Go back" link when the referring URL is known. In those awkward situations where no referring URL has been recognized, the function writes a "Go back" link via JavaScript.

Maximum and Minimum Height and Width in Internet Explorer

Posted on January 16, 2007 in Function, Presentation by Jeff Starr

Behold the seventh wonder of the virtual world: max/min-height and max/min-width properties are possible in Internet Explorer! Indeed, by taking advantage of IE’s proprietary CSS attribute, expression, you too can whip IE widths and heights into desirable proportions. The CSS expression attribute enables JavaScript commands to be executed within Internet Explorer. JavaScript via CSS? Thanks, Microsoft!

Why is this so great? Well, because in other, standards-compliant browsers, max/min-height and max/min-width properties are easily accomplished with this simple bit of CSS..

Continue Reading

Industrial-Strength Spamless Email Links

Posted on January 15, 2007 in Function by Jeff Starr

In our previous article on creating spamless email links via JavaScript, the presented method, although relatively simple to implement, is not the most effective solution available. Spambots, email harvesters, and other online scumbags relentlessly advance their scanning technology, perpetually rendering obsolete yesterday’s methods.

In the case of spamless email links created client-side via JavaScript, many spambots now are able to decipher certain email addresses hidden within the JavaScript code itself. Spambots scan JavaScript for keywords such as "email" or "mail", or even character strings containing ".com" or the "@" symbol. Spambots collect and decipher such data and return the favor with a flood of email spam.

Fortunately, the flexibility of JavaScript enables us to encode our email links as simply or as convoluted as needed. Indeed, our first post on spam-free email links focused on simplicity at the expense of long-term effectiveness, with multiple email addresses requiring multiple instances of the JavaScript function.

In this article we present a technique which obfuscates all email data within the JavaScript itself, making it virtually impossible for current technology to extract accurately any email addresses contained therein. This is a more durable, industrial-strength method for protecting your inbox from the spammers. Although slightly more complicated, this method accommodates multiple email addresses within a single, robust JavaScript function. So, without further ado..

Continue Reading

Auto-Focus Form Elements with JavaScript

Posted on December 4, 2006 in Function by Jeff Starr

After digging through the WordPress source code, I stumbled upon this very useful JavaScript method for auto-focusing form elements upon page load. Here is the JavaScript code (place within the document head):

<script type="text/javascript">
   function formfocus() {
      document.getElementById('element').focus();
   }
   window.onload = formfocus;
</script>

…and corresponding (X)HTML markup (abbreviated for clarity):

<form>
   <input id="element" />
   <input />
   <input />
</form>

In this example, the first form element (identified by id="element") will be automatically focused when the document loads, thus facilitating the process of entering data in the form. This technique would serve users well on login pages (wink, wink;), or anywhere forms are required on a repetitive basis.

Update: [ May 29th, 2007 ] - Here is a similar method of auto-focusing a form element with just a splash of JavaScript. Place the following code into an input element that contains a predefined field value and watch in amazement as the text string is automatically highlighted upon user focus. Here is the JavaScript snippet:

onfocus="this.select();"

..and here is a “live” example:

..and corresponding code:

<form action="http://domain.com/" method="post">
   <div>
      <input onfocus="this.select();" value="Select this input element and this text will be highlighted.." size="55" type="text">
   </div>
</form>

Preloading Images with CSS and JavaScript

Posted on November 14, 2006 in Function, Optimization by Jeff Starr

Fast-loading pages reduce errors, conserve bandwidth, and please visitors. One way to decrease loading times and enhance performance involves maximizing image display efficiency. Your mantra for achieving image efficiency should be "reuse, optimize, and preload.". While each of these methods plays an important role, this article will focus on methods for preloading images. Consult your server error logs to identify web pages that may require image help. Note: preloading images does not reduce bandwidth! It only decreases apparent load time, thereby enhancing user experience.

Preloading via the CSS Display Property

This method is a very common method for preloading images via the CSS display: none; directive. To use this method, first add the following code to your CSS rules:

<style type="text/css">
<!--/*--><![CDATA[/*><!--*/
   img.preload { display: none; }
/*]]>*/-->
</style>

Then, add the preload class to each image tag that should be preloaded:

<img src="image1.jpg" alt="Image Caption 1" height="33" width="33" class="preload" />
<img src="image2.jpg" alt="Image Caption 2" height="33" width="33" class="preload" />
<img src="image3.jpg" alt="Image Caption 3" height="33" width="33" class="preload" />
<img src="image4.jpg" alt="Image Caption 4" height="33" width="33" class="preload" />

Include the array of preloading image elements to the bottom of the home page, just before the body tag. Placing the images at the bottom of the page requires the browser to load the entire page before preloading any of the images. Finally, simply use the same image path and name when referencing the preloaded images on subsequent pages. The browser will have cached the images and will be able to load them instantly. Remember not to use the preload class for images that are meant to be displayed.

Preloading Tuf with JavaScript

This method uses JavaScript to cache specified images as the document is loaded. Images will then be displayed immediately as they are called. The JavaScript itself degrades peacefully and has no effect on browsers that do not support JavaScript. The script is as follows. Simply replace ../path/to/image-0n.gif with the corresponding path and name of the image to be preloaded. Then, simply call the images as normal (e.g., <img src="../path/to/image-0n.gif" alt="Image Caption" />) wherever they are required.

<script>
<!--//--><![CDATA[//><!--

if (document.images) {

	img1 = new Image();
	img2 = new Image();
	img3 = new Image();

	img1.src = "../path/to/image-01.gif";
	img2.src = "../path/to/image-02.gif";
	img3.src = "../path/to/image-03.gif";

}

//--><!]]>
</script>

You can also wrap this method in a function like so:

function preloader() {
	if (document.images) {

		var img1 = new Image();
		var img2 = new Image();
		var img3 = new Image();

		img1.src = "../path/to/image-01.gif";
		img1.src = "../path/to/image-02.gif";
		img1.src = "../path/to/image-03.gif";
	}
}

One Link to Open Them All

Posted on October 4, 2006 in Function by Jeff Starr

Welcome to Perishable Press! This article explains several methods for opening multiple frames with a single link. For more excellent (X)HTML information, check out the (X)HTML tag archive. If you like what you see, I encourage you to subscribe to Perishable Press for a periodic dose of online enlightenment ;)

Opening Multiple Frames with One Link

Method 1:

The first method of targeting multiple frames involves replacing either the entire frameset (via target="_top") or a subset of frames (via target="subset"). For example, any number of frames may be updated with a single link if that link targets a new frameset containing all of the new frames. Likewise, multiple frames within a nested frameset may be updated by replacing the nested frameset itself. This method works well when many frames need updating. In the following example, the nested frameset, "nested-frameset.html", contains multiple frames that need updating when a single link is clicked. When this happens, the "dynamic" frame is refreshed with multiple new frames, while the "static" frame remains constant. Using this method, virtually any combination of frames or framesets may be updated with a single link.

<frameset cols="*,3*">
   <frame src="static-content.html" name="static">
   <frame src="nested-frameset.html" name="dynamic">
</frameset>

Method 2:

The second method for targeting multiple frames employs JavaScript’s "onClick" function. With this method, the initial frame (or frameset) is updated via the link’s href attribute, while the additional frame(s)/frameset(s) is updated via the link’s onClick attribute. This method requires JavaScript, but is much less convoluted than the method previously discussed. In the following example, when the link is activated, "first-frame" will be updated with first-frame.html, while "second-frame" will be updated with second-frame.html:

<a href="/path/first-frame.html" 
 target="first-frame" title="Update frames" 
 onClick="top.second-frame.location='/path/second-frame.html';">
   Click here to update both frames.
</a>

Method 3:

Our third method of opening/updating multiple frames with a single click utilizes a simple JavaScript function. This method operates through a function call placed in either the href or onclick attribute of the anchor (<a>) element. Upon activation, the JavaScript function proceeds to open simultaneously the specified links. Implementing this technique is straightforward. Given the following frameset:

<html>
 <head>
  <title>The Frameset</title>
 </head>
 <frameset cols="50%,50%">
  <frame src="page-01.html" name="frame-one" />
  <frame src="page-02.html" name="frame-two" />
 </frameset>
</html>

…with the following code present in page-01.html, which is displayed as frame-one:

<html>
 <head>
  <title>Frame One</title>
  <script type="text/javascript">
   <!--//--><![CDATA[//><!--
    function openframes() {
       parent.frame-one.location="page-03.html";
       parent.frame-two.location="page-04.html";
    }
   //--><!]]>
  </script>
 </head>
 <body>
  <p>
   <a href="javascript:openframes();" title="Open two links..">
    Open "page-03.html" into "frame-one" and "page-04.html" into "frame-two"
   </a>
  </p>
 </body>
</html>

With the previous code in place, the broswer window will display two frames of equal width. In the left frame, there will be a link that, when clicked, will open two links at the same time. Specifically, when the link is clicked, a file named “page-03.html” will replace the contents of the left frame (”frame-one.html”) while a file named “page-04.html” will replace the contents of the right frame (”frame-two.html”). To setup additional frames to open/update upon link click, simply add the corresponding lines to the openframes() function by emulating the existing code pattern. For example, to add another three frames to the function:

function openframes() {
   parent.frame-one.location="page-03.html";
   parent.frame-two.location="page-04.html";
   parent.frame-thr.location="page-05.html";
   parent.frame-for.location="page-06.html";
   parent.frame-fiv.location="page-07.html";
}

Finally, to account for users without JavaScript, we could call the function via onclick attribute, include an alternate frameset or page via the href attribute, and throw in a return false declaration for good measure:

<a href="../no-javascript.html" onclick="javascript:openframes();return false;">
   Open "page-03.html" into "frame-one" and "page-04.html" into "frame-two"
</a>

Beyond frames..

Using the onClick attribute within links, it is possible to target more than just frames. For example, Monzilla’s Information theme for WordPress features subpanels that "pop" open to reveal various types of content. To improve usability, we wanted certain panel links to open their panels while simultaneously repositioning the top of the panel with the top of the browser. This was easily accomplished with an onClick attribute in each of the panel links1.

References

  • 1 To check out the "popping" subpanels used in the Information theme, click here, scroll down near the bottom of the page, and click on either the "nonsense" or "details +" tabs. The single link click should result in two events happening simultaneously: the subpanel will pop open and the subpanel will align its top edge with the top of the browser window.

Customize WordPress Quicktags

Posted on September 18, 2006 in Function, WordPress by Jeff Starr

Note: This condensed tutorial assumes you are working with WordPress 2+ and are familiar with editing .php and/or .js files.

WordPress quicktags1 provide shortcuts for adding certain bits of code to your posts. The default set of quicktags includes some handy shortcut buttons for tags such as <strong>, <a>, and <img>, as well as a few others. While the default set of quicktag buttons is occasionally useful, a quick bit of quicktag customization can easily transform your personal set of quicktag buttons into a deadly arsenal of time-saving code shortcuts.

First, open the quicktags.js file, usually located in the wp-includes/js directory. Next, scroll down to around line #40 and look for the following chunk of code:

edButtons[edButtons.length] = 
new edButton('ed_strong'
,'b'
,'<strong>'
,'</strong>'
,'b'
);

edButtons[edButtons.length] = 
new edButton('ed_em'
,'i'
,'<em>'
,'</em>'
,'i'
);

Now, to assist in the editing process, copy and paste this next bit of code in between any two of the edButtons[] statements. As this will be used as reference only, ensure that remains commented out:

/*

THIS IS THE GENERAL FORMAT OF A QUICKTAG BUTTON:

function edButton(id, display, tagStart, tagEnd, access, open) {
	this.id = id;             // used to name the toolbar button
	this.display = display;   // label on button
	this.tagStart = tagStart; // open tag
	this.tagEnd = tagEnd;     // close tag
	this.access = access;     // access key
	this.open = open;         // set to -1 if tag does not need to be closed
}

*/

With that in place, it is time to add a new button. Choose a code element that you find yourself frequently adding to your posts. Let’s say that you are always linking to a content directory called "content". In that case, let’s add a quicktag button that will automatically create a link to the content directory:

edButtons[edButtons.length] = new edButton('ed_content-link'
,'content-link'
,'<a href="http://yourblog.com/path/content/" title="">'
,'</a>'
,''
);

After saving and uploading the edited quicktags.js file, adding a link to your content directory is as easy as pressing the "content-link" quicktag button!

The process of adding other tags is essentially the same. Play around a bit and see what you come up with. Hopefully, this is enough information to get you started. Remember to delete the reference example after you have finished adding/editing buttons. For newer versions of WordPress, the same block of reference code is included near the top of the quicktags.js file itself. For more information on customizing quicktags, check out the tutorial2 listed in the reference section below.

References

Auto Clear and Restore Form Elements

Posted on August 29, 2006 in Function by Jeff Starr

Using a small bit of JavaScript, it is possible to auto-clear and restore form elements when users bring focus to them. Simply copy, paste, and modify the following code example to achieve an effect similar to this:

 
<form action="http://domain.com/" method="post">
   <p>
      <input value="Click here and this will disappear.." onfocus="if(this.value == 'Click here and this will disappear..') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Click here and this will disappear..';}" type="text" size="77" />
   </p>
</form>

Update [January 2nd, 2007] » Here is another auto-clear JavaScript trick that cleans up the (X)HTML code but does not auto-restore the element. Simply place the first code block into the document head (or external JavaScript file), and then flesh out form elements in the second of block of code and place within the document body:

<script type="text/javascript">
<!--//--><![CDATA[//><!--
   function m(el) {
      if ( el.defaultValue == el.value ) el.value = "";
}
//--><!]]>
</script>
<form method="post" action="<?php echo $PHP_SELF; ?>">
 <p>
  <input type="text" name="target" value="This will disappear upon user focus.." onFocus="m(this)">
  <input type="submit" name="submit" value="Submit">
 </p>
</form>

Optimize Convoluted Code via JavaScript

Posted on August 29, 2006 in Function, Optimization by Jeff Starr

Search engines loathe crawling through convoluted lines of code. Oceans of complex JavaScript scare away the priceless indexing and archiving efforts of most major search engines, which will generally abort a crawl upon encountering such mess. The good news is that search engines actually do not deploy JavaScript, so it is possible to use JavaScript to hide those miles of messy code by using the fundamental document.write function.

Place this function in an external JavaScript file, “navmenu.js”:

function navMenu() {
   document.open();
   document.write("<div>Convoluted code goes here.</div>");
   document.close();
}

Link to the external JavaScript file by placing this code in the document head:

<script src="js/navmenu.js" type="text/javascript"></script>

Finally, call the function by adding this to the target location within the document body:

<script type="text/javascript">
<!--//--><![CDATA[//><!--

   navMenu();

//--><!]]>
</script>

Spamless Email Address via JavaScript

Posted on August 28, 2006 in Function by Jeff Starr

[ Photo of Mr. T ] Let’s face it, spam sucks. Give spammers the figurative finger by using this nifty bit of JavaScript to hide your email address from the harvesters. Here is an easy “copy-&-paste” snippet for including a spam-proof email address in your web pages. Although there are a million ways of doing this, I am posting this for the record (and because I just can’t stand deleting usable code). This technique uses JavaScript, and therefore is not 100% ideal for all users. My advice would be to include a <noscript> element that contains an image of your email address. That way, users without JavaScript will still have access to your (spam-proof) email address. Of course, image-based text presents issues for text-only browsers, but hey, you gotta start somewhere! ;)

Spamless Email

Secure the function by adding this block of code to the document head, or by placing it within an external JavaScript file:

<script type="text/javascript">
<!--//--><![CDATA[//><!--

function email(name, domain, extension) {
   if (!document.write) return false;
   if (document.write) {
      var name; var domain; var extension;
      document.write('<a href="' + 'mailto:' + name + '@' + domain + '.' + extension + '">' + name + '@' + domain + '.' + extension + '<\/a>');
   }
}

//--><!]]>
</script>

Then, add this to the document body, replacing the three variables with real values:

<script type="text/javascript">
<!--//--><![CDATA[//><!--

email("name", "domain", "extension");

//--><!]]>
</script>

Finally, you may also add this line for those without JavaScript:

<noscript><p>(enable javascript or view source to see the email link)</p></noscript>

Or, you may wish to create a text-image of your email address for display on non-JavaScript machines:

<noscript>
   <img src="images/email.gif" alt="Email Address" class="noscript" style="border: 0px;" />
</noscript>

Specific Example

Here is an example of how the function may be configured on an actual web page. This is the specific code that we use at Monzilla Media to hide email addresses from the spamholes:

<script type="text/javascript">
<!--//--><![CDATA[//><!--

function email(m, o, n) {
   if (!document.write) return false;
   if (document.write) {
      var m; var o; var n;
      document.write('<p>Contact: <a href="' + 'mailto:' + m + '@' + o + '.' + n + '?subject=General%20Business" title="Contact">' + m + '@' + o + '.' + n + '<\/a><\/p>');
   }
}

//--><!]]>
</script>

<script type="text/javascript">
<!--//--><![CDATA[//><!--

email("m0n", "monzilla", "biz");

//--><!]]>
</script>

<noscript><p>(enable javascript or view source to see the email link)</p></noscript>