JavaScript: Using the Switch Statement

Posted by ActiveEnnovations

     As your programming skills grow, you move from small projects to bigger projects. As your projects get bigger, so does the amount of code they use. Even if the project does require a good amount of code, you will begin to look for shortcuts or faster ways to achieve a goal in the program. One such shortcut is the “Switch” statement. Using this statement in your program will essentially remove the need for a mess of “If…Else” statements. The ideal place for a “Switch” statement is in a program that offers the user options of what to do.

for example:

<script type= “text/javascript”>
var x= 2
switch(x)
{
  case 1:
   document.write(“One”);
   break;

  case 2:
   document.write(“Two”);
   break;

  case 3:
   document.write(“Three”);
   break;

  default:
   document.write(“Not One, Two, or Three”);
}
</script>

The example may be too simple, but it effectively shows the point. The value of variable ‘x’ is 2, so when the “Switch” statement is reached, it will jump to “case 2” and execute the code. The break statements after each case ensure that the code does not keep running through to the next cases.

Posted on: 8/17/2010 at 4:34 PM
Tags: ,
Categories: JavaScript
Actions: E-mail | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (11) | Post RSSRSS comment feed

Getting the Date & Time with JavaScript

Posted by ActiveEnnovations

An available pre-made object available to users in JavaScript is the Date object. This object can be used to retrieve the current date and time or to set the date & time. This object is handy for viewing the date & time on your website, or for doing comparisons between multiple times or dates. Utilize this object by creating a new Date object.

<script type= “text/javascript”>

var  makeDate= new Date(); /* Declares a new Date object with default settings. The default

function show()

{

var win=window.open("","details");

format is displayed as Day Month Date HH:MM:SS Time Zone Year*/

win.document.write("The Date Getters");

win.document.write("<br />");

win.document.write("Date=" + makeDate.Date());

win.document.write("<br />");

win.document.write("Day=" + makeDate.getDay());

win.document.write("<br />");

win.document.write("Month=" + makeDate.getMonth());

win.document.write("The Time Getters");

win.document.write("<br />");

win.document.write("Hour=" + makeDate.getHour(););

win.document.write("<br />");

win.document.write("Minutes=" + makeDate.getMinutes());

win.document.write("<br />");

win.document.write("Seconds=" + makeDate.getSeconds());

win.document.write("<br />");

}

// --></script>

<input onclick="show()" type="button" value="Show date/time details" /></p>

Posted on: 8/11/2010 at 8:06 PM
Tags: ,
Categories: JavaScript
Actions: E-mail | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (17) | Post RSSRSS comment feed

JavaScript : String Objects

Posted by ActiveEnnovations

JavaScript treats Strings as objects, and therefore there is a respective String Object Class that contains functions for manipulating the strings. This can make JavaScript very handy for manipulating the text without having to write all of the text formatting in html code.

 

<html>

<body>

<script type="text/javascript">

var line="I am a line of text";

document.write("Original lineence: "+line);

document.write("<br />");

document.write("blink, works in FF not IE "+line.fontcolor("orange").blink());

document.write("<br />");

document.write("toLowerCase() "+line.fontcolor("green").toLowerCase());

document.write("<br />");

document.write("toUpperCase() "+line.fontcolor("red").toUpperCase());

document.write("<br />");

document.write("toLowerCase() "+line.fontcolor("green").toLowerCase());

document.write("<br />");

document.write("big() "+line.big());

document.write("<br />");

document.write("small() "+line.fontcolor("red").small());

document.write("<br />");

document.write("bold() "+line.bold());

document.write("<br />");

document.write("italics() "+line.fontcolor("green").italics());

document.write("<br />");

document.write("fixed() "+line.fontcolor("brown").fixed());

document.write("<br />");

document.write("fontsize(5) "+line.fontcolor("green").fontsize(5));

document.write("<br />");

document.write('indexOf("h") '+line.fontcolor("green").indexOf("h"));

document.write("<br />");

document.write('lastIndexOf("l") '+line.fontcolor("green").lastIndexOf("l"));

document.write("<br />");

document.write("Superscript--sup() "+line.fontcolor("green").sup());

document.write("<br />");

document.write("Subscript--sub() "+line.fontcolor("green").sub());

document.write("<br />");

document.write("strike() "+line.fontcolor("red").strike());

var linked="Bertini Shoes";

document.write("<br />");

document.write("link() "+linked.fontcolor("green").link("http://www.bertini-shoes.com"));

</script>

 

</body>

</html>

This will produce the following output:

Posted on: 7/29/2010 at 10:31 PM
Tags: , ,
Categories: JavaScript
Actions: E-mail | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (14) | Post RSSRSS comment feed

JavaScript: Functions

Posted by ActiveEnnovations

            People who have done a little programming have no doubt written a method. Whether it is called a function or a method, is usually based on the language being used. JavaScript uses “function” for its naming convention. A function is essentially a container for lines of code to be executed when the function is called. Functions can be called when a webpage first loads up or as a response to a different page event, such as a button click.

            The two places of the HTML page to put JavaScript code is in the “head” section and the “body” section. The best place to put functions in a webpage is in the “head” section, placement here ensures that the code is pre-loaded when the webpage is opened. This avoids any potential conflicts with referencing functions that have not yet been loaded into memory.

 

A general function would be something like:

 function multiply(var a, var b)

{

  return a*b;

}

A simple example of a function call. Two numbers are passed to the function and the result is written to the webpage. In most real world cases the number input would be entered by the user.

<html><head>

      function multiply(var a, var b)

      {

          return a*b;

       }

</head>

<body>

<script type=”text/javascript”>

var x = 8;

var y = 7;

document.write(multiply(x,y)));

</script>

</body></html>

Posted on: 7/26/2010 at 3:52 PM
Tags: , , , , ,
Categories: JavaScript
Actions: E-mail | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (47) | Post RSSRSS comment feed

JavaScript: Loops

Posted by ActiveEnnovations

JavaScript: Loops

            The reason computers are practical is that they can repeat through portions of code, or loop, as a programmer would say. If a programmer had to write the same piece of code over and over again, computers would probably never have caught on.

            The main two looping forms utilized by programming languages and JavaScript are the “For” loop and the “While” loop. Both essentially serve the same purpose, but the way they operate is a little different. Loops run until an ending condition is met or the loop is escaped from. Loops make use of the logical and comparison operators discussed in the previous blog post.

The For Loop is set up with a counter and will increment after each iteration, until the end condition is met.

for example:  Variable “x” will start at one and repeat the code in the brackets while “x” is less than 11.

            var x=0;

for (x=0;  x<10; x++)

{

  document.write(“I will print this message 10 times.”);

}

The While Loop will run similarly to the For loop, with the exception that a counter is not implemented inside of the setup. With While loops, it is very easy to create an infinite loop if you don’t pay close attention to what you are doing.

for example:

var x = 0;

while(x<10)

{

 document.write(“I will print out 10 times”);

 x++; // If I was not here, the loop would go on an infinite number of times.

}

            A less elegant want to get out of a loop is by using a Break statement. While it is functional, it should be used sparingly.

Assuming the loops above, if something like this code was in there, the loop would stop.

      if(x == 2)
{

 break;

}

The statements would be printed two times if this was above the print statement, and three times if it was below it.

            If you want the loop to skip over a condition and not exit the loop, then a Continue statement should be utilized.

if(x==3)

{

   continue;

}

else

{

 document.write(“I will print this message 10 times.”);

}

The print statement would be executed 9 times, since it skipped printing when “x” was equal to three.       

Posted on: 7/22/2010 at 2:43 PM
Tags: , , ,
Categories: JavaScript
Actions: E-mail | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (4) | Post RSSRSS comment feed

JavaScript: Logic and Comparison Operators

Posted by ActiveEnnovations

JavaScript: Logic and Comparison Operators

            We all should remember the less than (< ) and greater than (>) from math classes back in school. Logical operators extended more into philosophy classes. The use of these symbols is widely used for comparisons and logical operations in numerous programming languages. The usage is not too much different that what it was back in our classes. The comparison symbols are used to indicate whether a value is less than, greater than, or equal to another value, while logical operators compare conditions to check if a  resulting condition is true or false.

The comparison operators:

“==” – A pair of sequential equal signs become the “Is Equal To” comparison

“===”-Three equal signs in a row becomes the “Is Exactly Equal To” comparison

“!=” – An exclamation point followed by an equal sign represents “Not Equal To”

“>” – An opening to the left still stands for “Greater Than”

“<” – An opening to the right still means “Less Than”

“>=”—Greater than or equal to

“<=”—Less than or equal to.

 

The logical operators:

“&&”- Two consecutive Ampersands represent a logical  “AND”.  Will compare two or more conditions and will return “true”, if all of the conditions are true. Otherwise the result is false.

“||”—Two consecutive pipes represents a logical “Or”. The result will be true if one or both of the compared conditions is true. It will only return “false” if both conditions are false

“!”—The Exclamation point is used to symbolize “Not”. Placing this in front of an expression will return the opposite of the resulting value.

Examples:

 Let A=True,  B=True, C=False

A && B = True          A || B= True    A && C = False    A || C=True     !A=False

 

Posted on: 7/20/2010 at 2:14 PM
Tags: , ,
Categories: JavaScript
Actions: E-mail | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (8) | Post RSSRSS comment feed

JavaScript : Variables and Operators

Posted by ActiveEnnovations

JavaScript : Variables and Operators

            While testing the JavaScript code on your website, there will be times that you will want to write notes to yourself or temporarily remove pieces of code. If you have worked with other programming languages before, you know that most have the capability of commenting out code so that it will not be run when the program is executed.

            To comment out a piece of code in JavaScript, you will need to use one of the following two delimiters:

// anything on this line after a double forward slash becomes unprocessed code.

/* the same goes for anything between these marks. This method is preferred for blocking out large portions of code.    */

            The point of programming is to be able to hold information and manipulate values, so the basic way to do this is with variables. There are no typed variables in JavaScript, a variable is just a value holder. As opposed to being typed as a number or text value, there is just the “var” keyword.

var number = 9;

var name = “jack”;

            This also means that you must be careful when manipulating the values. As “name + number” will produce a result. In this case “jack9”. For the most part arithmetic is done by using the symbols we have all come to use in math classes:

+: Addition.  It is also used to concatenate strings. Such was the case for “jack9” above.

-:  Subtraction

*: Multiplication

/: Division

Not so much in math classes, they are based on integer math:

%: Modulus or modulo will give you the remainder of a division.  (i.e. 7  % 3= 1)

++: Increments a number by 1.(i.e. 3++ = 4) You will usually use these with counters.

--: Decrements a number by 1. Also, usually used with counters.

Posted on: 7/13/2010 at 1:04 PM
Tags: , , ,
Categories: JavaScript
Actions: E-mail | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (14) | Post RSSRSS comment feed

Using JavaScript to Create Dynamic Content.

Posted by ActiveEnnovations

            The highlight of using JavaScript is that webpage content can be generated can be created dynamically, as opposed to being completely hard coded. One such example is that of the “write” function. The webpage in many cases will be referred to as the “document” object.

<html>

<body>

<script type="text/javascript">

document.write(<h2>The Title</h2>);

document.write(<p>The Content</p>);

</script>

</body>

</html>

            When the webpage loads, the html tags and their contents will be written into the page as if they were hardcoded into the page. Yes, the example is a bit goofy, but it is simplistic for this purpose. The uses of dynamic content can span into many fields of the website. Based upon a user’s answers or preferences a whole different block of text could be shown. This can be based on the user’s browser, age, gender, geographical location, and other such details.

 If the sex of the user is known, it could be used to change a reference to gender based words accordingly. Adding a “him” or “her” to the right positions adds an extra layer of personalization to a webpage. This gender personalization could also expand into the photos and advertising shown when they are viewing the webpage. The same customizations will follow for age and geographical location. The marketing purposes of this simple coding can go along way.

This practice has already been in use for a long time now. Did you ever notice the ads on Facebook that refer to the city you live in?  That is because they know where you live, or the general area anyways. And since you have an account there, they know specifics about you. It would be safe to assume that the ads guys see are not the same ads the young ladies see. They tailor the ads to what they believe your interests are.

Posted on: 7/9/2010 at 3:45 PM
Tags: , ,
Categories: JavaScript
Actions: E-mail | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (9) | Post RSSRSS comment feed

With JavaScript, Placement is the Key.

Posted by ActiveEnnovations

The most important thing to know about using JavaScript is where to place it in your webpage. Ultimately this will be based on what your code does and when it needs to trigger. The two places in a website that JavaScript can be placed is the head section and the body section. If you want the scripts to run when the page is loaded place your script code in the “body” section of your website. If you are creating functions that need to be called or triggered by event, this code will go in the head section. It will load when the page loads, but must wait for a function call to activate it. You can use both header scripts and body scripts in your page. There is no limit on the amount of JavaScript your page can contain.

A basic function call would be something as seen below. The JavaScript code is in the head section and does not run until it is called by the onload event of the body section.

<html>

<head>

<script type="text/javascript">

function showAnAlertBox()

{

alert("The alert() is a built in method that displays a message box.");

}

</script>

</head>

<body onload="showAnAlertBox()">

</body>

</html>

You can also save your script code into a text document and refer to it in you webpage. This would be a good way to cut down redundant code and keep the code readable.

<html>
<head>
<script type="text/javascript" src="functions.js"></script>
</head>
<body>
</body>
</html>

Posted on: 6/28/2010 at 11:58 PM
Tags: ,
Categories: JavaScript
Actions: E-mail | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (5) | Post RSSRSS comment feed

A Beginning Look at JavaScript.

Posted by ActiveEnnovations

A Beginning Look at JavaScript.

JavaScript has been in use almost as long as HTML itself. The main use of JavaScript is to add some dynamic behavior to websites, which means seeing results without having to wait for a page to refresh itself every time there is a change.

The main use of JavaScript in web pages adds the ability to:

  1. Dynamically generate HTML code into your webpage.
  2. Setup responses to events, like page loads and user clicks.
  3. Form Validation—JavaScript can code can check the information in the input fields is present and in the correct format.
  4. JavaScript can detect what web browser you are using and change to a webpage made for that browser. This used to be more important than it is now.
  5. JavaScript can be used in the passage and storage of information in cookies. This is usually the result of filling out a web form.

         To use JavaScript, one embeds scripting code into the HTML code of their web page. A basic example would be that of dynamically writing test. Normally this would be apart of an function called on a page load or if a button was clicked, but for the purpose of the example, this code is just in the body of the page and will run when the page is first loaded up.

<html>

<body>

<script type= “text/javascript”>

document.write(“document is the current web page being viewed. The red text is just for effect”);

</script>

</body>

</html>

Posted on: 6/21/2010 at 10:20 AM
Tags: , , ,
Categories: JavaScript | Web Design | HTML
Actions: E-mail | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (2) | Post RSSRSS comment feed