Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > Ajax and JavaScript

  • Print
  • + Share This
  • 💬 Discuss

Working with Functions That Return Values

(Netscape and Internet Explorer/Mac)

Up to this point, all the functions that we've seen simply do something and then return. Sometimes, though, we want to return a result of some kind. Script 3.9 (based on Script 3.2) checks on the fly to see whether or not the user has QuickTime enabled, instead of initializing a variable when the page first loads.

03fig21.jpg

Script 3.9 A function can return a value, which can then be checked.

To return a value from a function:

  1. function hasQT() {
      for (i=0; i<navigator.plugins.
      U2192.GIF length; i++) {
        if (navigator.plugins[i].name.
       U2192.GIF indexOf("QuickTime") >= 0) {
         return true
       }
      }
    
    The hasQT() function isn't passed any parameters, but it returns a value of true or false, depending on whether the user has the QuickTime plug-in installed. In this section, we return a value of true if at any point in the loop we find the QuickTime plug-in. Note that if a user has, for example, ten plug-ins, if QuickTime is the second one found, plug-ins 3-10 will never be checked. This can really help to speed up your code.
  2.    return false
    }
    
    If we've looped through every plug-in and never found QuickTime, we return false, signifying that QuickTime is not installed.
  3. if (hasQT()) { Here's where we use the function. Instead of checking an already set variable, we check on the fly to see if it's installed at this point. If it is, we see our movie, shown in Figure 3.13 .
    03fig22.jpg

    Figure 3.13 The QuickTime plug-in was found, so the script shows the movie.

  • + Share This
  • 🔖 Save To Your Account

Discussions

comments powered by Disqus