Week Five JavaScripting Notes

Tonight we are going to look at loops and conditions.

Introduction to Loops

Often when you write code, you want the same block of code to run over and over again in succession. Instead of adding the same lines multiple times in a script we can use loops to perform a task in repetition.

The JavaScript language provides two different kind of loops:

  • for - loops through a block of code a specified number of times
  • while - loops through a block of code while a specified condition is true

The for Loop

Syntax

for (var=startvalue;var<=endvalue;var=var+increment) {
   code to be executed
}

Example

Use the for loop when you know in advance how many times the script should run. For example, if you know you want to print the numbers 1 through 5 on a webpage:

<html>
<head>
<title>JavaScript Loop Example One</title>
</head>
<body>
<script type="text/javascript">
var i=0;
for (i=1;i<=5;i++) {
   document.write("The number is " + i);
   document.write("<br />");
}
</script>
</body>
</html>

The loop above will continue to run as long as i is less than or equal to 5. i will increase by 1 each time the loop runs because we've used the auto-incrementor operator (++).

The third for loop parameter could also be negative (in which case it would be called a decrementor), which then could be used in conjunction with a less than operator (< or <=) for the ending condition (the second for loop parameter). The first for loop parameter introduces the variable that will manage the loop and sets its initial value.

Other interesting for loop examples include generating factorials and generating prime numbers.

The while Loop

The while loop loops through a block of code while a specified condition is true.

Syntax

while (var<=endvalue) {
  code to be executed
}

Note: The <= could be any ending condition operator.

Example

The example below defines a loop that starts with i=1. The loop will continue to run as long as i is less than, or equal to 5. i will increase by 1 each time the loop runs:

Example

<html>
<body>
<script type="text/javascript">
var i=1;
while (i<=5) {
  document.write("The number is " + i);
  document.write("<br />");
  i++;
}
</script>
</body>
</html>


The do...while Loop

The do...while loop is a variant of the while loop. This loop will execute the block of code ONCE, and then it will repeat the loop as long as the specified condition is true.

Syntax

do {
  code to be executed
}
while (var<=endvalue);

Example

The example below uses a do...while loop. The do...while loop will always be executed at least once, even if the condition is false, because the statements are executed before the condition is tested:

Example

<html>
<body>
<script type="text/javascript">
var i=1;
do {
  document.write("The number is " + i);
  document.write("<br />");
  i++;
}
while (i<=5);
</script>
</body>
</html>

Using For Loops and a condition to test for Prime Number

<html>
<head>
<title>Determination of Primes</title>
</head>
<body>
<script type="text/javascript">
var i=0;
for(n=0;n<100;n++) {
    prime = true;
    for(t=2;t<n-1;t++) {
        if(n % t == 0) {
            prime = false;
            break;
        }
    }
    if(prime==true) {
        document.write(n + " is prime");
        document.write("<br />");
        i++;
    }
}
document.write("we found " + i + " prime numbers");
document.write("<br />");
</script>
</body>
</html>

JavaScript Conditions

Note: this section is adapted from an on-line tutorial.

Fairly often, we need a JavaScript to do different things under different conditions. For example, we might write JavaScript
code that checks the time every hour and changes some script variable appropriately during the course of the day. We
might write JavaScript code that can accept some sort of input, and act accordingly. Or we might write JavaScript code
that repeats a specified action where we need to identify the end condition.

There are several kinds of JavaScript conditions that we can use to test variable state. Conditional tests in JavaScript
are Boolean (named after the great philosophy logician Boole and therefore typically capitalized in text), so the result
of any test is either true or false. We can freely test values that are of Boolean, numeric, or of type String type in our
JavaScript code.

JavaScript provides control structures for a range of possibilities. Of all of them, the simplest control structures are
the conditional statements in JavaScript.

Explanation of JavaScript Conditions

JavaScript supports if and if...else conditional statements. In if statements a condition is tested, and if the condition
meets the test, some JavaScript code we've written is executed. In the if...else statement, different code is executed
if the condition fails the test. The simplest form of an if statement can be written entirely on one line, but multilane if
and if... else statements are much more common in Web development.

The following JavaScript Conditions example demonstrates syntax we can use with if and if...else statements.
The first example shows the simplest kind of Boolean test. If (and only if) the item between the parentheses evaluates
to true, the statement or block of statements after the if is executed.

Example of Using JavaScript Conditions

<html>
<head>
<title>If test</title>
<script>
var sky="grey";
function maleTest() {
   var elt = document.getElementById('gender');

   if (elt.options[elt.selectedIndex].text=='Male') {
      alert("Visitor is Male");  // Boolean test of whether (male) is true.
   } else if(sky=="blue") {
      alert("Sky is blue");  // Boolean test of whether (sky) is blue.
   } else if (elt.options[elt.selectedIndex].text=='Female') {
      alert("Visitor is Female");  // Boolean test of whether (male) is false.
   }
}
</script>

</head>
<body>
<form action="#" method="get">
<select id="gender" onblur="maleTest();">
<option value="None">
<option value="Female">Female
<option value="Male">Male
</select>
</form>
</body>
</html>

Another complete page example

<html>
<head>
<title>JavaScript Condition Example One</title>
<script type="text/javascript">
function setup() {
flower = document.getElementById('flower');
image = document.getElementById('image');
comment = document.getElementById('comment');
   if (image.src == "http://bdcampbell.net/javascript/flower.gif" && flower.style.backgroundColor == "rgb(0, 102, 0)") {
      comment.innerHTML="Isn't it a nice flower?<br>";
   }
}
</script>
</head>
<body onload="setup()">
<div id="flower" style="background-color:#006600;width:390px">
<img src="http://bdcampbell.net/javascript/flower.gif" id="image">
<span id="comment"></span>
</div>
</body>
</html>

JavaScript Conditional Operator

JavaScript also supports an implicit conditional form. It uses a question mark (?) after the condition to be tested rather than the word if
before the condition, and specifies two alternatives, one to be used if the condition is met and one if it is not. The alternatives are separated
by a colon here in JavaScript Conditional Operator.

Example of JavaScript Conditional Operator

var hours = "";

// Code specifying that hours contains either the contents of
// theHour, or theHour - 12.

hours += (theHour >= 12) ? " PM" : " AM";
document.write (hours);

Tip: If we have several JavaScript conditions to be tested together, and we know that one is more likely to pass or fail than any of the others,
depending on whether the tests are connected with JavaScript OR (||) or JavaScript AND (&&), we can speed execution of our JavaScript by
putting that condition first in the conditional statement. For example, if three JavaScript conditions must all be true using && JavaScript operators
and the second test fails, the third JavaScript condition is not tested.

Similarly, if only one of several conditions must be true using JavaScript || operators, testing stops as soon as any one condition passes the test.
This is particularly effective if the conditions to be tested involve execution of JavaScript function calls or other code.

An example of the side effect of short-circuiting is that runsecond will not be executed in the following example if runfirst() returns 0 or false as
shown below of our JavaScript Tutorial.

if ((runfirst() == 0) || (runsecond() == 0))

// some JavaScript code here

Condition Example

An example of using conditions with the opacity property with images

<div id='photoholder' style="position:relative;left:5%;top:176px;width:1012px;height:224px;z-index:500;background-color:#000030">
<img src='/images/fishes.jpg' alt='Photo' id='thephoto' />
</div>
<div id='animatedtext' style="position:relative;left:10%;top:310px;width:400px;height:110px;z-index:520;color:#FFFFFF;font-size:16px;font-family:'Trebuchet MS', Arial, Helvetica, sans-serif;background:transparent">
<a id='thelink' style="color:#FFFFFF;text-decoration:none" href="http://theoceanproject.org/communication-resources/market-research/">
<span id='thetext'>Click here to gain access to comprehensive research on public awareness, attitudes, and behaviors concerning the ocean, climate change, and related issues.</span></a> 
</div> 
<script language="javascript"> 
window.onload = function() {initImage()} 

function initImage() {
   imageId = 'thephoto';
   textId = 'thetext';
   linkId = 'thelink';
   image = document.getElementById(imageId);
   setOpacity(image, 100);
   image.style.visibility = 'visible';
   fade(imageId,100,0);
}

function setOpacity(obj, opacity) {
   opacity = (opacity == 100)?99.999:opacity;

   // IE/Win
   obj.style.filter = "alpha(opacity:"+opacity+")";

   // Safari<1.2, Konqueror
   obj.style.KHTMLOpacity = opacity/100;

   // Older Mozilla and Firefox
   obj.style.MozOpacity = opacity/100;

   // Safari 1.2, newer Firefox and Mozilla, CSS3
   obj.style.opacity = opacity/100;
}

/* The fade function uses a Timeout to call itself every 100ms with an object Id and an opacity. The opacity is specified as a percentage. */

function fade(objId,opacity,fcount) {
   if (document.getElementById) {
      obj = document.getElementById(objId);
      if (fcount < 10) {
         opacity = 100;
      } else if (fcount < 20) {
         setOpacity(obj, opacity);
         opacity -= 10;
      } else if (fcount == 20) {
         opacity = 0;
         document.getElementById(imageId).src="dolphin.jpg";
         document.getElementById(textId).innerHTML="Click here to make a contribution to<br/>help protect our ocean. Together,<br/>we will make a positive difference!";
         document.getElementById(linkId).href = "http://theoceanproject.org/donate/";
      } else if (fcount < 30) {
         setOpacity(obj, opacity);
         opacity += 10;
      } else if (fcount < 50) {
         opacity = 100;
      } else if (fcount < 60) {
         setOpacity(obj, opacity);
         opacity -= 10;
      } else if (fcount == 60) {
         opacity = 0;
         document.getElementById(imageId).src="boat.jpg";
         document.getElementById(textId).innerHTML="Click here to have your visitors take<br/>personal, community, and political action<br/>for the world's ocean.";
         document.getElementById(linkId).href = "http://theoceanproject.org/action/";
      } else if (fcount < 70) {
         setOpacity(obj, opacity);
         opacity += 10;
      } else if (fcount < 80) {
         setOpacity(obj, opacity);
         opacity += 10;
      } else if (fcount < 100) {
         opacity = 100;
      } else if (fcount < 110) {
         setOpacity(obj, opacity);
         opacity -= 10;
      } else if (fcount == 110) {
         opacity = 0;
         document.getElementById(imageId).src="ray.jpg";
         document.getElementById(textId).innerHTML="Click here to subscribe to our<br/>free monthly newsletter with innovative<br/>ideas and information for ocean conservation.";
         document.getElementById(linkId).href = "http://visitor.r20.constantcontact.com/manage/optin/ea?v=001Blh3vqF6HktWiNdBb6YJy41pzFfXNe2skrRzOS5Hz4HbqC_ZIB15tr-ZAGRJ2n22MsqIb7A4KL5YNOLLju1To6V3ja7UStPS_jGgZo4OC12riqKbaqlBrA%3D%3D";
      } else if (fcount < 120) {
         setOpacity(obj, opacity);
         opacity += 10;
      } else if (fcount < 140) {
         opacity = 100;
      } else if (fcount < 150) {
         setOpacity(obj, opacity);
         opacity -= 10;
      } else if (fcount == 150) {
         opacity = 0;
         document.getElementById(imageId).src="fishes.jpg";
         document.getElementById(textId).innerHTML="Click here to gain access to comprehensive research on public awareness, attitudes, and behaviors concerning the ocean, climate change, and related issues.";
         document.getElementById(linkId).href = "http://theoceanproject.org/communication-resources/market-research/";
      } else if (fcount < 160) {
         setOpacity(obj, opacity);
         opacity += 10;
      } else if (fcount == 160) {
         fcount=0;
      }
      fcount++;
      window.setTimeout("fade('"+objId+"',"+opacity+","+fcount+")", 150);
   }
}

The visual result (GET THE CODE)

Photo

The JQuery each Loop

The jQuery library provides a method, each(), which will loop through each element of the target jQuery object:

// Loop over each annual flower that meets the CSS specification for annual
$( "#flowers a.annual" ).each(
   // For each annual flower, run this code. The "indIndex" is the loop iteration index on the current element.
   function( intIndex ) {
      // Bind the onclick event to simply alert the iteration index value.
      $( this ).bind (
         function() {
            alert( "Annual flower index: " + intIndex );
         }
      );
   }
);

While there is nothing revolutionary going on here (although the bind method is a great addition to managing when JavaScript code runs), the beauty
of the each() method is that it creates a separate function scope for each loop iteration. For anyone who has tried to do a standard FOR-Loop in
which each iteration tries to dynamically set some object value, you probably have run into situation where all values post-loop are the same.

This has to do with when the variable is being bound.

By creating a separate function scope for each loop iteration, you basically eliminate all the "unexpected" variable binding behavior. Sweet! It seems
every time I step back and look at what jQuery is doing for us, it's simply stripping away more and more potential headaches at page run time.

 

Take a look at this online article about more examples of using the JQuery .each() method.