Styles – alter with javascript

To alter style values within a html page via Javascript can be done two different ways, that I know of, one is via getting the object itself and then altering the style from that and the other is via the document style sheets object.

The document style sheets object is all of the styles on the web page and is index within an array manor. For example

       styleSheet = document.styleSheets[<insert number of object>]

But since the two main browsers (Internet Explorer and also Firefox) deal with the css rules within this object with a different reference (IE = rules and FF = cssRules).

       if (styleSheet.cssRules)
              cssRule = styleSheet.cssRules[0]; // Firefox
       else if (styleSheet.rules)
              cssRule = styleSheet.rules[0];         // IE

The other method is via the id of the object, to obtain this just need to use the javascript getElementById function with the document object.

       cssRule = document.getElementById(style)

And then once the object of the style is obtained with both functions can just alter the style of the object with the same code.

       if (cssRule.style.backgroundColor == colour)
              cssRule.style.backgroundColor = colour2;
       else
              cssRule.style.backgroundColor = colour;

Here is the full code

<html>
       <head>
              <style language="text/css">
                     h1 { background-color: lightblue;}
                     #pstyle { background-color : lightblue;}
              </style>       
              <script language="javascript">
                     function alterh1(colour, colour2)
                     {       
                            var styleSheet, cssRule;
                            if (document.styleSheets)
                            {
                                   styleSheet = document.styleSheets[0];
                                   if (styleSheet)
                                   {
                                          if (styleSheet.cssRules)
                                                 cssRule = styleSheet.cssRules[0]; // Firefox
                                          else if (styleSheet.rules)
                                                 cssRule = styleSheet.rules[0];         // IE
                                          if (cssRule)
                                          {
                                                 if (cssRule.style.backgroundColor == colour)
                                                        cssRule.style.backgroundColor = colour2;
                                                 else
                                                        cssRule.style.backgroundColor = colour;
                                          }
                                   }
                            }
                     }
 
                     function alterstyle(style,colour, colour2)
                     {
                            var cssRule;
                            cssRule = document.getElementById(style);
                            if (cssRule)
                            {
                                   if (cssRule.style.backgroundColor == colour)
                                          cssRule.style.backgroundColor = colour2;
                                   else
                                          cssRule.style.backgroundColor = colour;
                            }
                     }
              </script>
 
       </head>
       <body>
              <h1>Change this style</h1>
              <input type="submit" value="click here" onclick="javascript:alterh1('blue', 'lightblue')"/>
 
              <p id="pstyle">
                     HI there
 
              <input type="submit" value="click here" onclick="javascript:alterstyle('pstyle','blue','lightblue')"/>       
       </body>
 
</html>

Arrays – Insert into a div

Javascript arrays are just like any other object orientated language, in the aspect an array is a block of memory associated with main object. To create an array in Javascript just need to call
= Array(5);
Or
= Array(‘value1′,’value2’);

The code below is using a default screen from which you press the ‘Click Here’ button and the array is used to insert into a <div> html tag. To insert into a div tag within javascript, there needs to be a new node created and in this instance a text node is created which in turn is appended to the div.

The code hopefully will explain more.

<html>
       <script language="javascript">
              // setup the main array
              var setArray = Array("hi", "there", "this", "is", "a","test");
 
              // insert the array into the DIV smalltest object
              function insertArray()
              {
                     var theText = "";  // set the theText output to an empty string otherwise it would start with null.
                     for (var i=0; i < setArray.length; i++)
                     {
                            // create the array of text to insert
                            theText += setArray[i];
                     }
                     // create the createTextNode 
                     var insertText = document.createTextNode(theText);
                     document.getElementById("smalltest").appendChild(insertText);
              }
       </script>
       <body>
              Just a small test, 
              <div id="smalltest">
              </div>
              <input type="submit" value="click here" onclick="javascript:insertArray()" />
       </body>
</html>

Add two numbers

This tutorial demonstrates how to get two inputs from the user within a HTML page and have a button on the page to call a javascript method to process the inputs and alter the answer output on the web-page.

Within HTML, there are input tags that allow the user to input data that is passed either to a javascript method to validate the inputs (for example a registration forum) or to pass data back to the server (after the validation has taken place if required).

The value 1 input is defined as
value 1 = <input type=’text’ id=value1 name=’value1′ value=’1’/>
the input type is text, which means any textual value, [A-Z]*[0-9]* but in this case since just adding integers [0-9] would be the required input.
The id is for getting the value from the input with using javascript document.getElementById, value is for setting the default value.

The function within the javascript, addNumbers() will get the inserted value1 by using the javascript document object. Within this object there is a method called getElementById that returns back the object, which in turn using the .value of the object returned can be passed to the parseInt (which converts a string value into a integer value). The same method is used for the answer input within the web-page (getElementById) but assign the return object to a variable allows access to the .value to set the value on the web-page.

The source code is

<html>
  <head>
        <title>Input tutorial</title>
        <script language="javascript">
                function addNumbers()
                {
                        var val1 = parseInt(document.getElementById("value1").value);
                        var val2 = parseInt(document.getElementById("value2").value);
                        var ansD = document.getElementById("answer");
                        ansD.value = val1 + val2;
                }
        </script>
  </head>
  <body>
        value1 = <input type="text" id="value1" name="value1" value="1"/>
        value2 = <input type="text" id="value2" name="value2" value="2"/>
        <input type="button" name="Sumbit" value="Click here" onclick="javascript:addNumbers()"/>
        Answer = <input type="text" id="answer" name="answer" value=""/>
  </body>
</html>

save as addtwonumbers.html and then open in a web browser (e.g. FireFox)

Hello world

Well, this is the javascript hello world. The javascript is used within web pages and the client browser (e.g. Internet Explorer or Firefox etc) will use the javascript code to help display the content of the page. This tutorial displays the “Hello World” in the webpage.

If you cut from

<html>
       <title>Javascript hello world</title>
       <body>
       <script language="javascript">
              document.write("Hello World!");
       </script>
       </body>
</html>

as javascripthelloworld.html

and then open up within IE or FF, this shall display a white page with the words in the top left “Hello World!”

The javascript is based on Objects, the same as Java,C++, C# etc, and the document object is the web page itself.

Hope it helps

Arrays

Arrays are ways of having a block of memory allocated to a single variable type, this allows for holding the national lottery numbers within an array of 6 instead of actually having 6 different variables, saves on variable overload

e.g.

int value1 = 1;
int value2 = 2;
int value3 = 3;
int value4 = 4;
int value5 = 5;
int value6 = 6;

and instead you could just have

int[] values = {1,2,3,4,5,6};

This is example code of how to use arrays.

public class arraytest
{
       public static void main(String[] args)
       {
              // the main method passes in parameters from the console command line 
              // e.g. ./arraytest hi there, hi there are two parameters
              for (int i =0; i < args.length; i++)
              {
                     System.out.println(args[i]);
              }
 
              // to create a array of numbers
              int[] intarray = {0,2,3,4};
 
              for (int i =0 ; i < intarray.length; i++)
              {
                     System.out.println(intarray[i]);
              }
       }
}

After compiled the above code and executed the class file that would be generated by

Java arraytest hi there

The output of the program would be

hi
there
0
2
3
4

But if the console command line was empty then just the number values would be outputted since they are inserted into the code and the ‘hi there’ was inserted manually on the command line.

Interfaces

An interface describes what functions an implemented class will have to code. E.g. if a class was a car and the interface had functions for how many doors etc, then a class of Vauxhall that implements the interface would have to code the function to return the correct amount of doors.

Here is the code, I usually find the code explains it better.

// defines the fuctions that have to be implemented by a implementable class
interface implementThese
{
       void printHi();       // have to implement these
       void printBye();
}
 
// the interClass will implement the interface implementThese
class interClass implements implementThese
{
       public void printHi()
       {
              System.out.println("Hi");
       }
 
       public void printBye()
       {
              System.out.println("Bye");
       }
}
 
class inter
{
       public static void main(String args[])
       {
              interClass in = new interClass();
              // call the classes functions.
              in.printHi();
              in.printBye();
       }
}

If you save as inter.java, and then run the output will be

Hi
Bye

There can be many interfaces per class to be implemented.

Generics

A Generic is a way to declassify the type of variable used, e.g. if there was a function to add up two integer values, but you had two double values, then the int function would not function correctly, so there would be a need to function overload the function to allow for the double increment as well. But just envisage that the same function would be required for characters, floats, personally created ones etc, then there would be more functions per type of variable than the actual work done.

A generic class negates this by allowing any class type passed to the function, as long as the type has the standard increment process defined, it will work with any type.

This will demonstrate the basics of the generics.

// the class for the generics (the T is the object of any type)
class genericsClass<T> 
{
       T val;              // private object val of type T
       public genericsClass(T t)       // constructor for the class
       {
              val = t;              // set the internal to the passed value
       }
 
       public T returnValue()       // return the internal value
       {
              return val;
       }
}
 
// main runable class
public class generics
{
       public static void main(String args[])
       {
              // create a Integer class with a default value of 3
              genericsClass<Integer> genInt = new genericsClass<Integer>(3);
              System.out.println("Value= " + genInt.returnValue());
 
              // create a String class with a default value of "hi there"
              genericsClass<String> genStr = new genericsClass<String>("hi there");
              System.out.println("Value = " + genStr.returnValue());
       }
}

If you save the code and run with java version 1.5 + (since this was part of java 1.5). The output will be

Value = 3
Value = hi there

As you can see the same class is able to use both integer and strings as the default variable type.