How I may help
LinkedIn Profile Email me!
Call me using Skype client on your machine

Reload this page Javascript Coding

Here are my notes on coding Javascript files for dynamic web pages.

 

Topics this page:

  • Examples
  • Timeline
  • Dynamic HTML
  • HTML Tutorials
  • JavaScripting
  • Javascript Coding
  • Cascading Styles
  • JavaScript & Microsoft Document Object Models
  • Client-side Data Binding
  • Cookies
  • Server Side Scripts
  • Your comments???
  •  

    Site Map List all pages on this site 
    About this site About this site 
    Go to first topic Go to Bottom of this page


    Related:

  • Javascript Sample Page
  • Date & Time Programming
  • Coding to Specify Color
  • Application Development
  • Web Project Plan
  • Web Development Tools
  • Java Programming
  • JavaScript Libraries

    Javascript Examples Used In This Site



    Go to Top of this page.
    Previous topic this page

    Timeline For Markup Languages

    • HTML Support History
    • 1991 Microsoft introduces Visual Basic and VBScript
      1995 JavaScript Created by Brendan Eich of Netscape based on the Standard Generalized Markup Language (SGML) defined as ISO 8879:1986

      Microsoft releases Internet Explorer 3.0 by renaming Javascript JScript .

      Dec. 1996 Cascading Style Sheets, level 1 (CSS1) page presentation recommendation is released. Both Microsoft and Netscape promise adherence to the standard, and implemented CSS1 in version 4.0 of their browsers. Netscape's Scott Thurman and Microsoft's Scott Isaacs co-wrote CSS1.
      July 1997 ECMA-262, also known as ECMAScript, is released by Microsoft as JScript 3.1.
      July 1997 HTML 4.0 draft specification issued by W3C provides enhanced table and form support.
      Microsoft's VBScript site
      98 Extended Markup Language (XML) is used to define the object, methods, properties, etc., and script to provide the functionality to write server <scriptlet> elements. This functionality is processed by Internet Explorer 5.
      May 98 CSS2 Recommendation published by the W2C.
      June 98 Microsoft releases IE5 with support for XML, dynamic expressions, fixed-layout tables, and dynamic behaviors.
      Oct 99? Microsoft releases Windows 2000 (Millenium) with IIS 5.
      - Javascript accepted as ISO-16262
      - Dynamic HTML (Collection of Tutorials) from Netscape
      Oct 04 Firefox 1.0 officially released by Mozilla

      W3C's SMIL (Synchronized Multimedia Integration Language) standard (and *.smil file extension) integrates digital snapshots with audio commentary. If your browser doesn't support it, get the

    • Real Networks plug-in free (but uncheck "other file types" so it doesn't hijack other file types.
    • MathML (Math Markup Language) was defined to describe mathematical symbols.

      The main competititor to Javascript is Macromedia Flex.

    Browser Product Language Version
    NN2+ & IE3+ JavaScript 1.0
    IE3+ only VBScript
    NN3+ only JavaScript 1.1
    NN4+ JavaScript 1.2 Guide and Reference (DHTML)
    IE4+ JScript 3 (DHTML)
    IE5 JScript 5
    IE5.1
    WSH 2another page on this site
    JScript 5.1
    Only Netscape recognizes <SCRIPT language= "Javascript 1.1">. IE will ignore it. Likewise, Netscape ignores language="VBScript" container tags.

    BooK recommendation: “Hybrid HTML Design: A Multi-Browser HTML Reference” (ISBN: 1562056174) by Kevin Ready and Janine Warner, provides a good guidance on coding HTML for multiple browsers.

    Go to Top of this page.
    Previous topic this page

    DHTML

      No W3C specification formally defines DHTML (Dynamic Hypertext Markup Language), a marketing term applied to a mixture of standards defined by Microsoft (against) the W3 Consortium of organizations in the internet community.

      However, XHTML1 extends HTML 4.0 and XML 1.0 to provide Extended Forms handling.

      W3C says IE 5 “includes a number of experimental features which uses a CSS-like syntax but which are not part of any W3C specification.”

      Microsoft has since submitted their DHTML spec to W3C for consideration as a standard.

      Microsoft defines the term dynamic as the ability to alter content at runtime . Netscape's definition of dynamic is limited to user-defined changes only at load time and switching layers at runtime.

      Microsoft's propriety enhancements to HTML,are implemented through a combination of multimedia objects and ActiveX Controls, include:

      • light filters which create an artificial tint
      • blends of several colors,
      • Alpha Channel transparency effects to dissolve text into an image or to create a faint watermark background image which doesn't tile or move.
      • Dynamic table generation of HTML tables automatically from a database server and progressively displayed and even resorted by the IE browser.
      • Data binding of database records to Web page objects.

      The hierarichical nature of the Object Model provides for event bubbling where the definition of action events "bubble" up all the way to a global style sheet for a site which defines default handling.

     

      Go to Top of this page.
    Previous topic this page

    Basic HTML Coding

      <HTML>
        <HEAD> </HEAD>
        <BODY>
          <form id="_id0" method="post" action="/a4j-simpleRepeator/demo.jsf" enctype="application/x-www-form-urlencoded">
          Input text:
          <input type="text" name="_id0:_id3" value="" onkeyup="A4J.AJAX.Submit('_viewRoot','/a4j-simpleRepeator/demo.jsf',this,{'parameters':{'_id0:_id4':'_id0:_id4'}})" size="50">
          Response:
          <span id="_id0:repeater">
          <input type="hidden" name="_id0" value="_id0">
          </form>
        </BODY>
      </HTML>

      Favicon (Favorite Icon)

      The .ico file in the HEAD section associates the favicon (pronounced fav-eye-con) with the page. The favicon.ico file contains image files (See favicon.com)
      • 16x16 pixels for display next to to the site's name on the client's IE5 Address Bar and Favorites.
      • 32x32 pixels for thumbnail displays
      • 256 colors for current systems
      • 16 colors for display on system trays.

      This specific link is required when HTTPS is used, or the default favicon will not be displayed.

    Go to Top of this page.
    Previous topic this page

    The Basic Elements of Scripting Style

      Here are my notes on the basics elements of Javascript:

      • Objects — groups data together with functions.
      • Variables — provides a place to store data.
      • Arrays — holds a great deal of data and access individual elements easily.
      • Expressions — performs operations on data.
      • Functions — groups code into sections with a name.
      • Flow Controlanother page on this site — enables programs to take different courses of action at runtime.

    • Surround all script coding between a single set of <SCRIPT> and </SCRIPT> tags.
    • Place scripts between <head> and </head> tags to be executed once on entry. For example, script code self.blur(); tells the window to "lose focus" and makes the window "jump behind" the window currently in focus.
      Script code self.resizeTo(100,200); resizes the window to the number of pixels from the left upper corner of the screen.
    • Invoke functions with <body onload="dothat();dothis()"> rather than with window.onload=dothis from within the script.
    • Notice that a semicolon ; separates each Javascript statement .
    • Invoke script upon loading as a BODY attribute: <BODY init="javascript:func1;"
    • A window that shouldn't go away is made modal by

      <body onblur="self.focus();">

    • Within a script block, start individual in-line comments with // and surround multiple lines of comments between /* and */ tags.
    • Place // at the same indent level as the code it comments.
    • Place // at the outer left edge only temporarily during debugging.
    • Hide script code from older browsers by surrounding code between <!-- and --> tags, without additional comment text.

    • Surround each block of script statments between curly brackets { and }
    • Surround text strings between 'single quotes' within a function and if a "double quotation mark" is in the string.

    • To print a web page without showing page information, so the only thing printed is the content of a web page, do not use the TITLE tag but code

      onload='document.title="My Title";window.print()'

     
      Go to Top of this page.
    Previous topic this page

    Variables in Javascript

    • Variable names must begin with an alpha or underline character.
    • As with UNIX and C, JavaScript is case-sensitive.
    • To paint a password <INPUT TYPE="PASSWORD" NAME="pwd" AUTOCOMPLETE="OFF" >

      Only IE5 recognizes the AUTOCOMPLETE="OFF" attribute.

      Operators (such as and, or, not, etc.) are used in expressions .

      Boolean operators are either true or false. A numeric expression which evaluates to zero results in a Boolean false.

    • What operation does the following expression do?

      16 % 3

      Answer: Division? No. It's Modulo -- the remainder of a division problem. In this example, the result is 1, the remainder of 16 divided by 3.

    • What operation does the following expression do?

      currPosition += 10;

      Answer: Adds 10 to the variable currPosition.

     

      Go to Top of this page.
    Previous topic this page

    Flow Control

      An "id=" defined in CSS can only be used once on a page/document.

      However, a "name=" can be specified several times within HTML.

      To use Javascript to flip between serif and sans-serif faces (and blue to green) when users move their mouse on a link:

      <SCRIPT language="JavaScript">
      function mytext_onmouseover() {
      mytext.style.fontFamily = "serif";
      mytext.style.color = "mediumseagreen" }
      </SCRIPT>
      ...
      <BODY>
      <DIV ID = mytext STYLE = "FONT-FAMILY: garamond, serif;
      FONT-SIZE: 16pt; COLOR: blue; "
      onmouseover="mytext_onmouseover()";
      onmouseout="mytext_onmouseout()">
      </DIV>

      This code fragment inserts the URL of the webpage:

      <script language="JavaScript">
      document.write('<input type=hidden name=u value=');
      document.write(document.URL);
      document.write('>');
      </script>

      The ID associated with a DIVision tag allows that tag to be manipulated as an object.

      Only Internet Explorer supports <MARQUEE>, hover, and Cascading Style Sheets in full.

      <BLINKING> is only supported by Netscape. Thank goodness.

      To get the scrollbar to show on the left (to flip the whole a layout Arabic style):

      <textarea dir="rtl">

      HTML 4.0 introduced a new bdo backward direction object tag that spells "backward" as backward

        <bdo dir="rtl"> backward </bdo>

      To disable the Submit button, in the form, add onsubmit="return disableForm(this);" to call this function

        // from http://javascript.internet.com/forms/disable-submit.html#source
        function disableForm(theform) {
        	if (document.all || document.getElementById) {
        		for (i = 0; i < theform.length; i++) {
        			var tempobj = theform.elements[i];
        			if (tempobj.type.toLowerCase() == "submit" 
        			|| tempobj.type.toLowerCase() == "reset")
        			tempobj.disabled = true;
        		}
        	}
        }

    Go to Top of this page.
    Previous topic this page

    Window

      The (blue) title at the top of the window displays the value of

      document.title

      The Window status bar at the bottom

      self.status
      Javascript feature A clock is there because of RecursiveClock() running in the <HEAD> section.

      To break out of frames:

      if (parent.frames.length > 0){
      	parent.location.href = location.href;
      }
      To open a new window:

      function popUp(URL,title) {
         eval(title+" = window.open(URL,'" +title+ 
      	"',toolbar=0,scrollbars=0,location=0,
      	statusbar=0,menubar=0,resizable=0,
      	width=500,height=500,
      	left = 250,top = 35"); 
      	");
      }
      Method window.close();" is called to close a window:

      For a page to close itself automatically, in its body tag:

      <body onLoad="setTimeout('window.close()', 
      10000);">

      10000 means 10 seconds.
      1000 means 1 second.

     

      Go to Top of this page.
    Previous topic this page

    Cascading Style Sheets

      A style sheet file houses a group of style rules which define font face, color, size, margins, etc. for a page design. Cascading Style Sheet files have a file extension of .css . Within the HEAD block (between <head> and </head> tags): Typically, they are dynamically included into an HTML file by adding the <LINK> tag for simpler, older browsers (except for ie4.5mac, which makes text small, even when (the few) users increase font size to largest.

        <link rel="stylesheet" href="nn4.css" type="text/css" media="screen" />

      For newer browsers, specify style sheet in an URL @import statement.

        <!--link before import prevents Flash Of Unstyled Content in ie6pc -->
        <style type="text/css" media="screen">@import url("real.css"); </style>

        Styles in this file override the nn4.css styles.

      Style specifications are enclosed between <style> tags. This example defines the default font for the page:

        <style type="text/css">
        body { font-family: Verdana; Tahoma, Ariel, "Times New Roman", non-serif; }
        </style>

      This table describes stylesheet rules, which are composed of selectors and declarations that define how styles will be applied. The selector (a redefined HTML element, class name, or ID name) is the link between the HTML document and the style. There are two different kinds of selectors: types (HTML element tags) and attributes (such as class and ID names). A CSS declaration has two parts: a property ("color") and a value ("red"). The basic syntax of a rule selector {property 1: value 1; property 2: value: 2} " An example (containing two declarations) P {font-size: 8pt; color: red}

     


    Go to Top of this page.
    Previous topic this page

    CSS Rules

      Selector
      tag
      name
      Declaration 1 Declaration 2
      Property 1 Value 1 Property 2 Value 2
      Types (HTML element tags):H2 {font-size:8pt;color: red }
      Attributes:.Class Name:P {font-size:8pt;color: red }
      #ID Name: body { background:white;color: black; }


    Go to Top of this page.
    Previous topic this page

    Generate HTML

      The following Javascript generates all the body HTML of a page using W3C's DOM Level 1 - interface. Counter var j is used to define rows. Counter var i is used to define columns.

      <HTML><HEAD><script>
         function start() {
            var mybody=document.getElementsByTagName("body").item(0);
            mytable = document.createElement("TABLE");
            mytablebody = document.createElement("TBODY");
            for(j=0;j<2;j++) {
               mycurrent_row=document.createElement("TR");
               for(i=0;i<2;i++) {
                  mycurrent_cell=document.createElement("TD");
                  currenttext=document.createTextNode("cell is:"+i+j);
                  mycurrent_cell.appendChild(currenttext);
                  mycurrent_row.appendChild(mycurrent_cell);
      
                  mytablebody.appendChild(mycurrent_row);
               }
               mytable.appendChild(mytablebody);
               mybody.appendChild(mytable);
               mytable.setAttribute("border","2");
            }
         }
      </script>
      </head>
      <body onload="start()">
      </body>
      </html>
      

      NOTE: The code above uses native JavaScript. But most front-end UI developers now use jQuery instead.

      Veena Basavarajpresents at LinkedIn blogged and spoke about using the Dust.js library after evaluating other isomorphic JavaScript templating engines.

      Dust bills itself as a "Less Logic".

      Dust can run on both browser client machines AND on servers (on Rhino with Java via JNI and V8 with C++ programs).

      JSON data is most commonly retrieved from a node.js using Express to respond to API requests from the browser.

      Dust is used to move away from JSP with XML.

      Dust can be compiled for better performance.

      Lynda.com has a course on JavaScript Templating.

      Dust uses curly braces to insert sections within HTML markup. If/then logic.

      Helpers include

      -


    Go to Top of this page.
    Previous topic this page

    JavaScript Reflection

      The method document.getElementsByTagName("body") returns a list of all the elements in the document that have tag named "body", which is available by default (does not need to be created like the other elements.

      If you view the source from the internet browser, you will only see the code above, unless you install add-ins:


    Go to Top of this page.
    Previous topic this page

      HTML Element Tags

      HTML element tags define how text is presented. For example, <H1> around an element of text defines the size and boldness of that text. "H1" is called a style selector .

      Classes

      Classes are used to create grouping schemes among styled HTML tags by adding the style definition of a particular class to the style definitions of several different tags. In the stylesheet, a class name is preceded by a period (.) to identify it as such:
      .foo {property 1: value 1; property 2: value 2}
      A very simple example:

      <style>

      P {font-family: sans-serif; font-size: 10pt}
      H1 {font-family: serif; font-size: 30pt}
      H2 {font-family: serif; font-size: 24pt}
      .red {color: red}
      .green {color: green}
      .blue {color: blue}

      </style>

      The tags and classes can then be used in combination:

      <h1 class="red">This is rendered as 30-point red serif text.</h1>

      <p class="red">This is rendered as 10-point red sans-serif text.</p>

      Or not:

      <p>This is rendered as 10-point sans-serif text in the default color.</p>

      The ID attribute is used for a uniquely defined style within a stylesheet. In the stylesheet, an ID name is preceded by a hash mark (#) to identify it as such:

      #foo {property 1: value 1; property 2: value 2}
      <h2 id="foo">Text rendered in the foo style.<h2>

      Text-Level Attributes: <SPAN> and <DIV>

      The <span> tag is generally used to apply a style to inline text:

      <p><span class="foo">This text is rendered as foo-style</span> and this is not.

      The <div> tag is generally used to apply a style to a block of text, which can also include other HTML elements:

      <div class="foo">
      <p>The "foo" style will be applied to this text, and to <a href="page.html">this text</a> as well.
      </div>

      The style attribute provides a way to define a style for a single instance of an element:

      <p style="font-size: 10pt; color: red">This text is rendered as red, 10-point type</p>

      The class, ID, and style attributed can be applied within the <span> and <div> elements. Used with class or ID, the <span> and <div> tags work like customized HTML tags, letting you define logical containers and apply a style to their contents.

      This code defines the POSITIONing of a container for text to be displayed:

        <BODY>
        <DIV ID = mytext STYLE = "POSITION: relative;
        WIDTH: 40%;
        FONT-FAMILY: garamond, serif; FONT-SIZE: 16pt; COLOR: blue; ">
        <P> Text to be displayed. </P>
        </DIV>
        </BODY>

      DynamicDrive.com offers this tip for defining a watermark image:

      <script language="JavaScript1.2">
      if (document.all)
      document.body.style.cssText="background:white
      url(notebook.jpg) no-repeat fixed center center"
      </script>

     

     
    Go to Top of this page.
    Previous topic this page

    No Right Clicking

      To disable right clicking to make it harder for pictures to be copied and stolen, use this code from Marsha Collier, eBay guru

      <SCRIPT LANGUAGE="JavaScript1.1">
      function right(e) {
      if (navigator.appName == 'Netscape' &&  (e.which == 3 || e.which == 2))
        return false;
      else if (navigator.appName == 'Microsoft Internet Explorer' &&  (event.button == 2 || event.button == 3)) {
        alert("YOUR BUSINESS NAME");
        return false;
      }
      return true;
      }
      document.onmousedown=right;
      document.onmouseup=right;
      if (document.layers) window.captureEvents(Event.MOUSEDOWN);
      if (document.layers) window.captureEvents(Event.MOUSEUP);
      window.onmousedown=right;
      window.onmouseup=right;
      // End -->
      </script>

     
    Go to Top of this page.
    Previous topic this page

    Javascript Object Model


    Go to Top of this page.
    Previous topic this page

    Microsoft Document Object Model

      MS-DOM




    Go to Top of this page.
    Previous topic this page

      Widow.Open Options

      Option Description
      dependent(JavaScript 1.2) If yes, creates a new window as a child of the current window. A dependent window closes when its parent window closes. On Windows platforms, a dependent window does not show on the task bar.
      directoriesIf yes, creates the standard browser directory buttons, such as What's New and What's Cool.
      height(JavaScript 1.0 and 1.1) Specifies the height of the window in pixels.
      hotkeys(JavaScript 1.2) If no (or 0), disables most hotkeys in a new window that has no menu bar. The security and quit hotkeys remain enabled.
      innerHeight(JavaScript 1.2) Specifies the height, in pixels, of the window's content area. To create a window smaller than 100 x 100 pixels, set this feature in a signed script. This feature replaces height, which remains for backwards compatibility.
      innerWidth(JavaScript 1.2) Specifies the width, in pixels, of the window's content area. To create a window smaller than 100 x 100 pixels, set this feature in a signed script. This feature replaces width, which remains for backwards compatibility.
      locationIf yes, creates a Location entry field.
      menubarIf yes, creates the menu at the top of the window.
      outerHeight(JavaScript 1.2) Specifies the vertical dimension, in pixels, of the outside boundary of the window.
      personalbar(JavaScript 1.2) If yes, creates the Personal Toolbar, which displays buttons from the user's Personal Toolbar bookmark folder.
      resizableIf yes, allows a user to resize the window.
      screenX(JavaScript 1.2) Specifies the distance the new window is placed from the left side of the screen.
      screenY(JavaScript 1.2) Specifies the distance the new window is placed from the top of the screen.
      scrollbarsIf yes, creates horizontal and vertical scrollbars when the Document grows larger than the window dimensions.
      statusIf yes, creates the status bar at the bottom of the window.
      toolbarIf yes, creates the standard browser toolbar, with buttons such as Back and Forward.
      width(JavaScript 1.0 and 1.1) Specifies the width of the window in pixels.

    Go to Top of this page.
    Previous topic this page

      Elements in the DOM

      textrange refers to the entire document .

      element.outerHTML
      refers to the entire element -- all text and HTML tags of the element.

      element.innerHTML
      refers to the text and HTML tags nested between HTML paragragh <P> tags. (such as <I> or<B>).

      element.outerText
      refers to all of the text stream and inner HTML tags.

      element.innerText
      refers to the text stream between tags nested within other tags. Changes to this value would leave formatting unchanged.



      -

     
    Go to Top of this page.
    Previous topic this page

    Client-Side Data Binding

      This example is implemented in the Sortable HTML Entity Codes web pageanother page on this site.

      The GUID for the CLASSID in this example points to the Microsoft Tabular Data Control (TDC) that shipped with all versions of IE4. It retrieves (for read-only access) the entire text file to the client IE4 browser. This ActiveX Data Source Object (DSO) — a part of Microsoft's OLE-DB API — uses the HTTP protocol and COM interface mechanisms to enable sorting and filtering on the client machine.


        <BODY ...

        <OBJECT id=companies
        classid="clsid:333C7BC4-460F-11D0-BC04-0080C7055A83"
        border="0" width=0 height=0>
        <PARAM name="DataURL" value="entcode.txt">
        <PARAM name="UseHeader" value=True>
        </OBJECT>

        <DIV DATAsrc= "#companies"DATAFLD="Name"></DIV>


        <TABLE DATAsrc="#furniture" border="1">
        <TRvalign="top"><TD>
        <SPANDATAFLD="Name"></SPAN> < BR></TD><TD align="right">
        <SPANDATAFLD="Price"></SPAN> < BR></TD><TD align="right">
        <SPANDATAFLD="Items"></SPAN>
        </TD><TD>
        <SPANDATAFLD="LastInventoryDate"></SPAN> < BR></TD><TD>
        <SPAN DATAFLD="Image" DATAFORMATAS=HTML ></SPAN>
        </TD>
        </TR>
        </TABLE>

      When the UseHeader attribute value is True, DATAFLD refers to the field names specified in the first line of the text file rather than default field names "Column1", "Column2", etc. For example, user header name "Price:INT" specifies the price field as an integer. "picture:HTML" specifies the picture field as containing HTML code which needs to be interpreted.

        Name,Price:Float,Items:INT,LastInventoryDate:Date,Image:HTML
        XXYYZZ,123.34,8,09/22/1999,<IMG src=xxyyzz.gif>

     

      With TDC, only data is downloaded for the browser to format. This is instead of using document.write() Javascript code and wrapping HTML page formatting code around data.

      The <OBJECT tag defines the data source on the web server which the <DATAsrc="data source" and <DATAFLD binds to <SPAN or <DIV data consumers presented within <TABLE tags. (<SPAN does not work with single record retrievals.)

      This approach is faster for users, gives them better control, and allows for more server scalability.

      RDC to access SQL databases is needed to write data back to the server.

      To encode a string to HTML entity codes:

        function htmlEncode(s)
        {
        return s.replace(
        /[<>&]/g,
        function(m) {
        return "&" + m.charCodeAt(0) + ";";
        });
        }
        

     
    Go to Top of this page.
    Previous topic this page

    Cookie Programming

      Cookies are set by the server sending a cookie set command within the header of the HTTP response from the server.

      Once a cookie has been sent, the web browser returns the cookie information back to the webserver on each subsequent request to the server until the cookie expires or is deleted.


    Go to Top of this page.
    Previous topic this page

    Browsers Optimizing Engines

      Browser Optimizing Engine Name
      Chrome V8
      Safari 4+ Nitro
      Firefox 3.5+ TraceMonkey
      Opera 10/11 Carakan

      CKEditor is a WYSIWYG HTML text editor for web content creation by bringing common word processor features to web pages. It's free, open source for community maintenance.

      $49 CK Packager compresses Javascript.

      Speed up Javascript load time

      tool Compress HTML removes unnecessary white space and characters such as carriage returns, line feeds, spaces and tabs. It can also remove certain HTML tags.

      tool HTMLProtector offers 2 JavaScript based encryption methods to protect web page content by preventing visitors from printing the page and viewing your source code, It also stops spam robots from extracting email addresses from your pages and automated downloads of your entire web site to their hard drive.


    Go to Top of this page.
    Previous topic this page

    Portions ©Copyright 1996-2014 Wilson Mar. All rights reserved. | Privacy Policy |


    How I may help

    Send a message with your email client program


    Your rating of this page:
    Low High




    Your first name:

    Your family name:

    Your location (city, country):

    Your Email address: 



      Top of Page Go to top of page

    Thank you!