Why is this page text-only?

Results tagged “javascript” from Code Scene

Compressing Prototype and Script.aculo.us

 If you're doing web development these days there's a good chance you've used the Prototype and Script.aculo.us JavaScript libraries.  They're both excellent and free libraries which make time-consuming JavaScript tasks much much simpler.

The only problem with them is that they're not exactly small.  If you just want to add some simple scrolling or fading effects to a page, you're looking at adding 160KB of JavaScript files... ouch.

Enter Protoaculous, a version of the scripts combined and compressed to minimize load times.  The compressed version now adds only 39KB to your site.  If all you need is the Script.aculo.us effects library you could use a version which weighs in at only 27KB.

I used it on a site I recently built and everything seems to work great.  I highly recommend using this tactic to minimize the load times on your sites.

Download the Protopack zip file here

Side note:  A recent post of the WebDriven Blog alerted me to another option to solving this problem in Google's new AJAX library API.  With this, you can let Google host the prototype (or jQuery, mooTools, and dojo) libraries for you.  In theory since these scripts will be pulled from Google's ultra-fast servers, it should help speed up your load times as well.  I've yet to try this approach but would be interested in hearing from anyone who does.

Prototype.js Cheat Sheet

Just a really quick post today for something that I think will come in handy.  I was catching up on some blog reading today when I stumbled across a great cheat sheet that someone has put together for the Prototype framework.

Cheat sheets are a great way to familiarize yourself with any new language or framework.  This PDF catalogs the full Prototype API, while denoting in red which methods have been deprecated in version 1.6.  It's well worth the download.

Prototype 1.6.0.2 Cheat Sheet

There's also a great Prototype checklist on the site to make sure you're getting the most of out the library.

Book Review: DOM Scripting by Jeremy Keith

I've had time lately to do a lot more reading and Jeremy Keith's DOM Scripting book is another one that belongs on your shelf if you're trying to learn any amount of JavaScript.  I've hated and avoided JavaScript for years, mostly because I started my career during the browser wars and quickly grew tired of having to write different code for different browsers.  Thankfully, those days are now mostly over and this book has made me love JavaScript again.

The Document Object Model (DOM) is a standard for conceptualizing and representing the contents of an HTML or XML type document.  Mr. Keith's book teaches how to use JavaScript to manipulate the DOM so that you can dynamically add or remove content from a page, change the way things look, or move things around.  Similar to how CSS allows you to control the presentation of your content, DOM scripting allows you to control behaviors and events.

There are lots of great JavaScript frameworks available like jQuery, Script.aculo.us, or Dojo which allow you to easily enhance your websites.  In order to fully take advantage of them though, you need to have a fundamental understanding of how things like the DOM and JavaScript event handling work.  That's where this book really excels.  It's written primarily for web standards developers fluent in XHTML/CSS who're looking to branch into more client-side scripting.

This book is full of useful lessons and real world examples on how to make JavaScript and the DOM work in your applications. It also places a heavy focus on fundamentals and best practices such as graceful degradation which will help you make sure that your sites still function well even without the fancy JavaScript enhancements.  JavaScript has long been thought to make things inaccessible but it doesn't have to be.  This book stresses how to use these technologies in an efficient, unobtrusive way.

What I liked most about this book was the voice in which it was written.  I've read dozens of boring hard-to-follow tech manuals over the years but this book felt more like a friend standing over your shoulder and walking you through the process.  That does somewhat limit the amount of information the book can cover and it definitely doesn't go very far into advanced techniques.  If you've been doing standards development and basic JavaScript for a while though, and you really want to get started on increasing your scripting skills, this book makes an excellent primer.  For me it turned my impression of JavaScript from an overly-complex annoyance to an easy-to-use yet incredibly powerful tool for improving my websites.

 

Rollover images with unobtrusive DOM scripting

There are about a million different scripts out there for doing JavaScript rollover images. Most of them however, aren't very good. They often require multiple functions... one to preload the images, one to swap them on rollover, and another to swap them back. Worse still, they usually involve inserting JavaScript event handlers into your HTML code.

Just look at the HTML code inserted by Adobe Dreamweaver's rollover function:

<a href="#" onmouseout="MM_swapImgRestore()" onmouseover="MM_swapImage('myImage','','images/myimage_o.jpg',1)"><img src="images/myimage.jpg" name="myImage" border="0" id="myImage" /></a>

This code is obtrusive and difficult to manage. Wouldn't it be great if you could just do something simple, like adding a CSS class, to make the rollovers work automatically? By using some scripting with the Document Object Model you can do that quite easily.

Here's a great rollover script written by Daniel Nolan that will allow us to greatly simplify our code. Take a look the HTML code needed to do the rollovers using this method.

<a href="#"><img src="images/myimage.jpg" class="imgover" /></a>

This is definitely much cleaner and easier. All we need to do is add the class="imgover" to our img tag and the script does the rest. When the page loads, the JavaScript looks through all of the img tags on the page. For each img tag it finds with the "imgover" class, it will dynamically add the onmouseover and onmouseout events to replace the images. It automatically looks for an image of the same name with "_o" at the end for the rollover. So if your main image were named myimage.jpg, you'd name the rollover image myimage_o.jpg.

That's all there is to it. Quick, easy, standards-compliant rollover images.

Download the rollover.js file.

Script.aculo.us Accordion and LightWindow

These days I spend more of my time in meetings and putting out fires than I do actually writing cool new bits of code, which is one of the reasons for the infrequent blog postings. Since I'm not writing as much code these days I can at least point out some of the cool work being done by other people.

Kevin Miller of Stickman Labs has provided two great components based on the script.aculo.us framework; Accordion and LightWindow.

Accordion is a great way to add collapsible panels where one panel closes as another one opens. This is a great way to organize pages which have lots of content, like a Frequently Asked Questions page or perhaps organizing some navigation elements on a page.

LightWindow is similar to Lightbox and other modal/pop-over window controls. It uses AJAX to pull content from the server dynamically and display it overlayed on top of the current page. What differentiates it from the rest is that it supports virtually any kind of conent. You can use it to load images, flash movies, video files, other HTML content, web forms, etc. It's easy to setup and there are lots of options you can tweak to make it work for your site.

Both controls can add cool functionality to your site and they're incredibly easy to install and use. Check them out and start enhancing your applications.

Lastly, people like Mr. Miller dedicate a lot of time creating projects like this for the rest of us to use. While he offers these free of charge, please consider supporting him and the community in general by making a donation. Hopefully this will encourage him to keep creating great work like this.

VS 2008 JavaScript Intellisense

I don't like being the type of blogger that writes a post that simply links to someone elses post.  Today though, I'm doing just that because:

  • I'm way too busy at the moment to write original content
  • I just think this is awesome
 

If you're an ASP.NET developer and you're not already reading Scott Guthrie's blog, start.  Seriously, go add the RSS feed to your reader right now.

His latest post on Visual Studio 2008 JavaScript Intellisense is great and very exciting if you're like me and don't particularly like writing javascript.  I honestly never learned javascript as well as I should have and until recently have avoided it wherever possible. Now that AJAX has taken the dev world by storm, avoiding javascript is no longer really possible.  Thankfully, VS2008 promises to make the learning curve a lot easier by providing the same type of helpful intellisense that we already know and love from writing .NET code.

It will work for in-line scripts as well as external .js files.  Writing and debugging javascript is about to get a whole lot easier.

Building your first Google Map

Mashup seems to be the latest buzz word and Google Maps seems almost ubiquitous these days. While the challenge of using the Google Maps API may seem daunting, it's actually not nearly as difficult as you'd imagine. Having recently tackled my first one I thought I'd put together a quick step-by-step guide on how to setup the basics for anyone else who may be interested in doing the same.

Step 1 - Obtaining your Google Maps API Key
Point your browser to http://www.google.com/apis/maps/signup.html, fill out the form and get your free API key. You need this in order to make your mashup work online. Embed it into the head tag of you page like so:

<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=INSERT-KEY-HERE" type="text/javascript"></script>

Step 2 - Plotting your points
For the purposes of this example I'm picking a few of my favorite restaurants in Washington, DC. While you can easily hard-code these into the Google Maps javascript, I think including them in an external XML file makes it easier to make updates so I've taken that route. My XML looks like this:

<markers>
   <marker lat="" lng="" name=" " phone=”" address="" city="" state="" zip="" url="" />
</markers>

Each marker on the map is represented by a node in the XML doc with attributes that will be used for the display of the map. Note that Google Maps uses latitudes and longitudes to plot markers. While there is a built in function to convert address into lat/long values (a process called geocoding), it wouldn't be efficient to call it for these static locations so I've included the geocoded values into the XML. To batch geocode a bunch of address values I recommend http://www.batchgeocode.com/

Step 3 - HTML Setup
In order for your map to show up within your site you'll need a simple div tag which will house the information from Google.

<div id="googlemap" style="width: 500px; height: 325px"></div>

You can give it whatever ID you like and adjust the width and height accordingly.

Next you'll need to initialize the map by adding some javascript to the HTML body tag like so...

<body onload="load()" onunload="GUnload()">

Step 4 - Javascript
This is where the actual magic happens. All of the settings for drawing the map and plotting the markers are handled via javascript. The following code will show you how to draw a basic map and plot the markers we defined earlier in our XML document.

<script type="text/javascript">
//<![CDATA[
var map = null;

function load() {
   if (GBrowserIsCompatible()) {

      var i = 0;

      // Create the map
      // Make sure this element has the same ID as your div
      map = new GMap2(document.getElementById("googlemap"));
      // Add controls for moving and zooming the map. Use GSmallMapControl for small maps
      map.addControl(new GLargeMapControl());
      // Add controls for switching between regular and satellite views
      map.addControl(new GMapTypeControl());
      // Set the starting position and zoom level when the map loads
      map.setCenter(new GLatLng(38.895222, -77.036758), 13);

      // Read the data from XML
      var request = GXmlHttp.create();
      // Open the XML file
      request.open("GET", "map-markers.xml", true);
      request.onreadystatechange = function() {
         if (request.readyState == 4) {
            var xmlDoc = request.responseXML;
            // Obtain the array of markers and loop through it
            var markers = xmlDoc.documentElement.getElementsByTagName("marker");

            for (var i = 0; i < markers.length; i++) {
               // Obtain the attribues of each marker
               var lat = parseFloat(markers[i].getAttribute("lat"));
               var lng = parseFloat(markers[i].getAttribute("lng"));
               var point = new GLatLng(lat,lng);
               var name = markers[i].getAttribute("name");
               var phone = markers[i].getAttribute("phone");
               var address = markers[i].getAttribute("address");
               var city = markers[i].getAttribute("city");
               var state = markers[i].getAttribute("state");
               var zip = markers[i].getAttribute("zip");
               var url = markers[i].getAttribute("url");
               // Call the function to create the marker
               var marker = createMarker(point,name,phone,address,city,state,zip,url);
               map.addOverlay(marker);
            }
         }
      }
      request.send(null);

      // Function to create the marker and set up the event window
      function createMarker(point,name,phone,address,city,state,zip,url) {
         // Create the HTML text based on the values passed in from XML
         var markerhtml = "";
         if (name != "") markerhtml += "<b>" + name + "</b><br>";
         markerhtml += address + "<br>" + city + ", " + state + " " + zip + "<br>";
         if (phone != "") markerhtml += "Phone: " + phone + "<br>";
         if (url != "") markerhtml += "<a href=\"" + url + "\">" + url + "</a>";

         // Create the map marker
         var marker = new GMarker(point);
         // Add a click event to each marker which will open the HTML window
         GEvent.addListener(marker, "click", function() {
            marker.openInfoWindowHtml(markerhtml);
         });
         i++;
         return marker;
      }
   }
   // Javascript alert for older browsers where Google Maps isn't supported
   else {
      alert("Sorry, the Google Maps API is not compatible with this browser");
   }
}
//]]>
</script>

That's basically all there is to it...

Google Maps Demo of this code in action

Download the source files

Further reading

Much of what I know was learned with a lot of help from these two sites.

The Google Maps API is incredibly complex and you can do much more more than what I've outlined here. Hopefully this post will serve as a baseline and help you get started building your own mashups.

JavaScript popups... The right way

This isn't about whether or not you should use popup windows. Everyone hates popups these days but sometimes they're necessary so you should code them properly. I'm always surprised because 90% of sites still do them wrong so here's a quick tip.

Here's how the majority of sites I see have their popup windows coded...

The Not So Good Way

<a href="#" onClick="window.open('whatever.html', 'windowName', 'width=200,height=200');">My Link</a>

The problem with this approach is that the link is entirely embedded in the javascript onClick event so the link will only work via javascript. Why do we care? Two reasons:

  1. Accessibility - Screen readers generally do not have javascript enabled so these links won't work for those users with visual impairments. There are also a small percentage of users who have simply disabled javascript, possibly out of security concerns.
  2. It annoys people like me - As a Firefox user I have a tendency to scan the page and middle-click on any link that looks interesting. This opens each link in a new tab (IE users often right-click and select 'open in a new window'). This lets me read multiple pages without having to click the back button a bunch of times. All hail tabbed-browsing. Popups coded this way prevent me from doing this.

So how should you be coding popup links? Here's the way I like to do it...

The Better Way

<a href="whatever.html" onClick="window.open(this, 'windowName', 'width=200, height=200'); return false;">My Link</a>

This embeds the link in the href attribute where it belongs and uses the javascript 'this' method to reference it. This way the popup works for regular users via the javascript but the link will still work the old fashioned way for screen readers and firefox tabbing. Obviously I'm using inline javascript here but you could easily break this out in a function if you plan on having multiple popup windows on the same page.

Scalable Inman Flash Replacement (sIFR)

One of the major limitations of web design is the number of available fonts. Traditionally, designers have been limited to "web safe" fonts like Arial, Verdana, and Times. These work well for all of the main page copy but most designers I know like to use nicer looking fonts such as Futura, Univers, or Trade Gothic for things like headers and pull-quotes.

For years, developers have handled this the only way they knew how... Photoshop. 150 pages meant 150 GIF files of rendered text. This solution is obviously time consuming and makes maintenance a nightmare.

Enter Scalable Inman Flash Replacement (sIFR). In a nutshell, sIFR lets you take CSS-styled text and, using some fancy javascript, dynamically replace the text with a Flash SWF file of the text rendered in the font of your choice.

Since this replacement is done dynamically, the underlying (X)HTML code isn't affected. Users with the Flash plug-in installed will see the intended special font. Users without will instead just see regular CSS-styled text in a fallback font such as Arial. Search engines and screen readers can also easily pick up the underlying text without problems.

See an example page using sIFR

A word of caution… As with any trendy new technique, sIFR should be used in moderation. While it is pretty efficient, you're still creating Flash files on the fly and dynamically replacing text using javascript. This is a great technique for things like headers but it wasn't really designed to replace massive blocks of text so keep that in mind when you implement it.

For more information see:

Fun with style sheet switching

One of the great things about building your websites using web standards is that the content is completely separated from the design. Since the design is controlled entirely through CSS it becomes simple to change. Add a style sheet switcher to your site and you can even let your users control the design. Click the colored buttons below (or on the right nav) for a demonstration.

Red Orange Yellow Green Blue Purple

Now why exactly would you want to give your users control over how your site looks? For CodeScene, I've done it simply because I think it's a cool trick that illustrates the separation of content and presentation. A far more practical use however, would have been to create styles with varying levels of font sizes and contrast. This would add to your site's accessibly by allowing the user to choose the style sheet that is most comfortable for him/her to read. Since CSS also controls not only the colors but the layout, you could use a style sheet switcher to control that aspect as well to perhaps show/hide a navigation bar. Use your imagination.

For those interested in the code behind it, it's a relatively simple javascript library that turns alternate style sheets on and off, and then sets a cookie to remember which one was selected. It was written by Paul Sowden and can be found in the article Alternative Style: Working With Alternate Style Sheets on the infamous A List Apart.