CHAPTER 11
Incorporating JavaScript

Even if you are not a programmer, or not familiar with JavaScript, you can still make use of this powerful language using the classes in this chapter. With them, you can embed simple calculations or complex expressions within an object, just by placing them within a pair of special tokens.

You can also use these plug-ins to leverage the power of JavaScript for creating sections of conditional HTML, whether based on expressions of your choice, or using a special global keyword to identify the browser in use (such as Firefox, or Internet Explorer, and so on).

Once you’ve used these classes, I think you may find them so handy you’ll wonder how you ever managed without them.

PLUG-IN 91: Embed JavaScript (embedjs)

Using Plug-in 91, you can embed snippets of JavaScript within an object, without having to use <script> tags. This makes it easy for you to display the result of a calculation, or anything else that can be displayed by JavaScript.

For example, in Figure 11-1 a number of code snippets have been embedded within a paragraph of text, which have been evaluated with the results then inserted in their place.

Variables, Functions, and Properties

image

About the Class

When this class is encountered, the object using it is parsed to see whether it has any sections embedded within [[ and ]] tags. If so, these sections are evaluated as JavaScript code and the result returned by the evaluation is substituted for the entire section from the opening [[ to the closing ]].

image

FIGURE 11-1 A paragraph with several JavaScript snippets embedded in it

How to Use It

With this class, you have the ability to easily embed any JavaScript inline with text. For example, you might want to display the result of a simple calculation and can do so like this:

<div class='embedjs'>The result of 23.2 * 7 is [[23.2 * 7]].</div>

As you can see, you don’t need to know anything about JavaScript to use this class to display the result of arithmetic calculations. You can also access the global variable BROWSER, which is used by the PJ.js file to keep track of the current browser type. It will have a value such as “IE”, “Opera”, “Firefox”, and so on, and can be displayed like this:

<div class='embedjs'>Your browser is [[BROWSER]].</div>

You can also embed much larger sections of code by separating the expressions from each other with a semicolon, like this:

<div class='embedjs'> The multiplication table for the number 12 is
[[mystr = ''; for (myvar = 1 ; myvar &lt; 13 ; ++myvar) mystr += myvar
* 12 + ' '; mystr]]</div>

Or, if you prefer, you can format the contents like program code as follows (still ensuring that there are semicolons at the end of each statement except the final one, which is optional):

<div class='embedjs'>The multiplication table for the number 12 is
[[
   mystr = '';
   for (myvar = 1 ; myvar &lt; 13 ; ++myvar)
      mystr += myvar * 12 + ' ';
   mystr
]]
</div>

The output from this example is:

The multiplication table for the number 12 is 12 24 36 48 60 72 84 96 108
120 132 144

CAUTION In the for() loop of this example, the &lt; entity is used instead of the < symbol because placing the < within HTML confuses browsers, which expect an HTML tag to follow it. Likewise, you must use the &gt; entity where you need a > symbol. The only way you can use the < and > symbols is if the entire JavaScript snippet is encased in quotation marks, like this: “[[76 < 83.3]]”, which will return the value true.

Here’s the HTML used for Figure 11-1, in which I have highlighted the embedded JavaScript snippets in bold:

<div class='embedjs'>
   You are using the following browser: [[BROWSER]]. The square root of
   42 is [[Math.sqrt(42)]]. The value of the new variable 'count' is
   [[count = 0]]. After incrementing it the new value is [[++count]].
   The result of (64 / 3 + 128) / 3.2 is [[(64 / 3 + 128) / 3.2]].
</div>

As you can see, you can also create a new variable (such as count, in the preceding example), and then refer to it later in a web page (as long as you don’t make it local by prefacing it with the var keyword, in which case it will work only in the current code snippet).

If you make a mistake, such as introducing a syntax error, an error message will be displayed in red, instead of the result you were expecting. For example, the following is invalid:

<div class='embedjs'>The result of 66 x 87 is [[66 x 87]].</div>

The problem is that the x symbol is not a valid operator in JavaScript, and it should be replaced with a * symbol. Therefore, because the parser was expecting a semicolon following the 66, the preceding snippet will generate an output similar to the following:

The result of 66 x 87 is [SyntaxError: missing ; before statement]
The JavaScript
if (classname.search(/embedjs/, 0) != -1)
{
   Html(thistag, Html(thistag).replace(/[[([^]]*)]]/g,
      function()
   {
       arguments[1] = arguments[1].replace(/&lt;/g, '<')
       arguments[1] = arguments[1].replace(/&gt;/g, '>')

      try
      {
         return eval(arguments[1])
      }
      catch(e)
      {
         return "<span class='red'>[" + e + "]</span>"
      }
   } ))
}

PLUG-IN 92: If (if[expr])

If you’ve ever wished you could write conditional HTML, then you should find this class very handy, because with it you can display an object only if an expression evaluates to true. For example, in Figure 11-2, the screen grab was taken after midday; therefore, it displays the phrase “Good Afternoon”.

Variables, Functions, and Properties

image

image

FIGURE 11-2 Using this class, you can display objects only when conditions are satisfied.

About the Class

This class evaluates the expression following the class name and then displays the object only if the expression evaluates to true. If it is false, to prevent the object’s display it is simply encased within <!-- and --> HTML comment tags.

How to Use It

Use this class when you want to display objects only when certain conditions are met. For example, the following object is displayed only after midday:

<span class='if[now = new Date(); now.getHours() > 11]'>Afternoon</span>

What is going on here is that a new object called now is created from the current date and time using the Date() function. Then, the getHours() method of the now object is used to return the current hour between 0 and 23. This value is compared with the number 11 and, if it is greater, the contents of the <span> is displayed, which in this case is the word “Afternoon”.


NOTE Unlike its use in objects implementing the embedjs class, the direct use of the > symbol is acceptable in this case, because the entire contents of the class argument are enclosed within quotation marks, and therefore the > cannot be mistaken for part of an HTML tag.

Using the BROWSER Global Variable with this Class

Because browsers all work differently, the PJ.js library of JavaScript functions needs to know which browser is running, and therefore tweaks can be made to ensure all the functions have the same (or nearly the same) effect. You can use the global variable BROWSER that it creates for your own purposes, too.

For example, if you have written an application for the iPad tablet that you want to advertise, you could use the following code to display details about it only to people browsing your web page using that device:

<div class="if[BROWSER == 'iPad']">
  Check out our special app for iPad users…
  etc…
</div>

image

TABLE 11-1 The possible values of the BROWSER variable

Table 11-1 lists all the values that BROWSER may have, in order of determination. For example, if an iPod Touch device is detected, then the string “iPod” is assigned to BROWSER, even though the browser running is a version of Safari.

Here is the code used for Figure 11-2:

Good
<span class='if[now = new Date(); now.getHours() < 12]'>Morning</span>
<span class='if[now = new Date(); now.getHours() > 11]'>Afternoon</span>
The JavaScript
if (classname.search(/if/, 0) != -1)
{
   origcname.replace(/(if|IF)[([^]]*)]/, function()
   {
      if (!eval(arguments[2]))
         Html(thistag, '<!-- ' + Html(thistag) + ' -->')
   } )
}

PLUG-IN 93: If Not (ifnot[expr])

Plug-in 93 provides the inverse of the if[] class and is useful for implementing the equivalent of an if… else… block of code. For example, in Figure 11-3 this class is used in conjunction with the if[] class, and you can see the different results displayed in the Apple Safari browser and in Internet Explorer (the inset).

image

FIGURE 11-3 Using both the if[] and ifnot[] classes to target different browsers

Variables, Functions, and Properties

image

About the Class

This class evaluates the expression following the class name and then displays the object only if the expression evaluates to false. If it is true, to prevent the object’s display it is simply encased within <!-- and --> HTML comment tags.

How to Use It

You use this class in the same manner as the if[] class, except that the object will be displayed only if the result of the expression in the square brackets evaluates to false. For example, here is the code used for the screen grabs in Figure 11-3:

I see you are using
<span class="   if[BROWSER == 'IE']">Internet Explorer</span>
<span class="ifnot[BROWSER == 'IE']">a browser other than IE</span>

Of course, you could replace the second line with the following, in which the if[] class is used in place of ifnot[], but with a modified expression:

<span class="if[BROWSER != 'IE']">a browser other than IE</span>

But the point of the ifnot[] class is that you don’t have to rewrite an expression that was used in an if[] class; you can simply copy the entire expression and place it within an ifnot[] class to achieve the inverse effect of the original, which is very handy if the expression is quite complex.


NOTE This completes all the dynamic classes in this book. In the next and final chapter, I’ll show you how you can combine any of these classes together to create superclasses, which have the combined functionality of many classes at once.

The JavaScript
if (classname.search(/ifnot/, 0) != -1)
{
   origcname.replace(/(ifnot|IFNOT)[([^]]*)]/, function()
   {
      if (eval(arguments[2]))
         Html(thistag, '<!-- ' + Html(thistag) + ' -->')
   } )
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.140.88