Saturday, November 10, 2012

A short guide to Java Script

Java Script

  • Also referred to as JS or Js.
  • JavaScript is the scripting language of the Web.
  • Major Aim was to energize and enhance the user's web experience.
  • Inspired by SELF programming language.
  • Object based, Interpreted, scripting language. The part of the web browser that runs the java script is called JavaScript Interpreter.
    • JavaScript is object based and not object oriented because it doesn't support Inheritance and Polymorphism. It have built-in objects like windows etc.
  • JavaScript does not use classes. JavaScript is prototype based, not class based.
  • Created by Brendan Eich at Netscape in December 1995. (Earlier it was called "LiveScript" before that it was called "Mocha").
    • European Computer Manufacturer's Association (ECMA) standardized the script and named it as ECMAScript.
  • JavaScript can be divided into three parts - 
    • Core Language (language fundamentals and syntax), 
    • Client-side (provides access to DOM and various browser objects) and 
    • Server-side (to code for server side standalone components of web application, access to server side objects). 
  • Client-side JavaScript is interpreted on the fly by the browser while Server-side JavaScript is first compiled into bytecode like Java. 
  • Server-side JavaScript is not covered here.
Features
  • JavaScript provides client side validations, so we are saved from passing data to server and reloading the page. Prior to JavaScript dynamic behavior was achieved with Server-side scripting.
  • JavaScript is case-sensitive.
  • A script can get the height and width of the browser window, client date as well as history of visited pages.
  • Alternate text can be provided, for occasions when JavaScript  support is absent or disabled with <noscript> </noscript>.
  • Cookie data is stored in the DOM document object's cookie property as one or more "name=value" pairs, in which the values may not contain any whitespace, commas, or semi-colon characters. 
  • Cookies can be set using document.cookie as well as readCookie and writeCookie method.
  • escape() and unescape() methods are used to encode/decode the strings - remove whitespace, etc other characters.
JavaScript and Security Concerns:
  • JavaScript doesn't allow you to read/write files on the user's hard drive. This limitation wipes out the potential for a lot of viruses. JavaScript doesn't support File Handling.
  • JavaScript doesn't support Network programming. It cannot establish a direct connection to any other hosts on the network. JavaScript program cannot use a client's machine as an attack platform from which to attempt to crack passwords on another machine.
  • Most browsers don't allow scripts to open or close windows without the user's approval. 
  • A JavaScript program cannot close a browser window without user confirmation unless it opened the window itself.
  • Access to cookies is restricted by owning websites.
  • JavaScript cannot be used to set the value attribute of a file input, and will not be allowed to use them to upload files without permission.
  • JavaScript cannot read what locations a user has visited by reading them from the location object, although it can tell the browser to jump back or forward any number of steps through the browser history. It cannot see what other Web pages the user has open.
  • It cannot see when the user interacts with other programs, or other parts of the browser window.
  • It cannot open windows out of sight from the user or too small for the user to see. JavaScript doesn't allow to open or resize the window to less than 100px.
  • A script may not cause a window or frame to display an about: URL, such as about:cache, because these URLs can expose system information, such as the contents of the browser's cache.
  • JavaScript is used as a "script engine" for other software components, such as ActiveX controls in Internet Explorer and plugins in Netscape. These may have file access and networking access.

<Script> Tag
  • Can be added anywhere in HTML, but its best to put it in <head> tag.
  • "type" attribute identifies the type of scripting language. Other scripting language examples are VBScript, ASP.Net AJAX etc. It actually specifies MIME type.
  • In addition to <script> tag, JavaScript code can be put directly into event handlers as well, its not a good practice and is done normally in case of a single line of code like an alert.
    <script type="text/javascript">
    function ...
    ....
    </script>

    <script type="text/javascript" src="myCustomJS.js"> </script>


Event
  • JavaScript mechanism that allows you to trigger a piece of JavaScript when something of interest happens to the page.
  • Events are initiated by users but they come from browser.
    <h1 onclick="alert('Hello');">Click Here</h1> //executing JS code
    <h1 onmouseover="change()">Hello</h1> // calling JS function
    document.getElementById("submitButton").onclick=displayName();
    document.getElementById("submitButton").onclick=function(){
        changeName();
        displayName()
    };
  • JavaScript event object has properties for type, target, altKey/shiftKey/ctrlKey gives true/false based on if for alt/shift/ctrl key was pressed, charCode/keyCode provides ascii code in case of KEY-related events etc
Event - Standard Event Model
  • With events defined in above section, we cannot Add and Remove Event listeners, Standard Event Model provides us ways to add/remove (attach/detach) event listeners.
    element.addEventListener(<type>, <JSFunction>, <use Capture>);
    element.removeEventListener(<type>, <JSFunction>, <use Capture>);
    element.attachEvent(<type>, <JSFunction>); // Old IE browser
    element.detachEvent(<type>, <JSFunction>); // Old IE browser
  • Bubbling is default behavior. (Google Bubbling and Capture for more information).
JavaScript variables, constants and data types
  • Three basic data types: string, number and boolean.
  • There are two other data types: function and object.
  • Data type are assigned to variables automatically depending on the value assigned, it changes with the change in value.
  • All numbers in JavaScript are stored as 64-bit (8-bytes) base 10, floating point numbers. There is no concept of int, long, and float.
  • false isn't exactly same as 0, but it converts to 0 when used where a number is expected.
  • The current variable type can be revealed by the typeof keyword. It returns a value of "undefined" for uninitialized variables.
  • Number.NaN, Number.POSITIVE_INFINITY, NUMBER.NEGATIVE_INFINITY, isNaN(), isFinite() are some key properties and methods.
JavaScript Functions
  •  There are two ways to define functions - 
    A. Using Function declaration:
    function test()
    {
       alert(test function);
    }

    B. Using Function expression (Assigning anonymous function to a variable):
    var test2 = function()
    {
       alert(test function);
    }
  • Approach B demonstrate that functions are variables in JavaScript. This approach is revisited in JavaScript objects.
  • Approach A on using function declaration are loaded first in the programs. Java script engines hosts function declaration to the top. It is possible to call the function before its declaration. It is not the case with function expression, it'll throw error.
    test();  // This will not error out and work normally.
    test2(); // This will error out 
             // because function expressions are not loaded first. 
    function test()
    {

       alert(test function);
    }
    var test2 = function()
    {

       alert(test function);
    }
  • A function can return another function.
    function testFunc(name)
    {
       return function()
       {
          var message = "Hello "+ name;
          alert(message);
       };
    }

    var func = testFunc("Prince");
    func();
  • To have variable arguments functions - use arguments keyword.
    function sum()    {
 
       total = 0;
 
       for (i=0; i < arguments.length;  i++)
 
       {
 
           total += arguments[i];
 
       }    }    var sumTotal = sum(100, 1, 2, 4);    document.write(total);
Objects
  • Memory area created by browser which represents an entity.
  • Almost everything is object in JavaScript in Java Script, ex Forms, Text field etc.
  • There are three ways to create objects:-
    • Define and create a direct instance of an object.
        <script>
            function customToString()
            {
                return this.firstname+" "+this.lastname;
            };

            var emp=new Object();
            emp.firstname="Prince";
            emp.lastname="Kapoor";
            emp.ID=7918;

            emp.customToStr = customToString;
            document.write(emp.customToStr());
   
    </script>
    • Using JSON to define an object.
JSON Ex 1:<script>
            var emp={firstname:"Prince",lastname:"Kapoor",ID:7918};
            document.write("Employee ID of "+emp.firstname + " is " + emp.ID);
        </script>

JSON Ex 2:<script>
            var emp=
            {  firstname:"Prince",
               lastname:"Kapoor",
               ID:7918,
               getOutputText: function() {
                  return "Employee ID of "+this.firstname + " is " +this.ID;
               }
            };
            document.write(emp.getOutputText());
        </script>
    • Using a prototype function to define an object, then create new object instances. (MOST PREFERRED)
      • By naming conventions, functions starts with small letter and constructors start with Capital letter.
Syntax: function object-name (param1, param2, param3)    
        {
            this.property1 = param1;
            this.property2 = param2;
            this.property3 = param3;
            this.method1 = function1;
            this.method2 = function2;
        }

Ex:     function Emp(firstname,lastname,id)
        // Above declaration could also be written as:
        // var Emp = function(firstname, lastname, id)
        {
            this.firstname=firstname;
            this.lastname=lastname;
            this.ID=id;
            this.getFullName = function ()
            {
                return this.firstname+" "+ this.lastname;
            }

        }

        var prince = new Emp("Prince", "Kapoor", 7918);
  • When we need multiple objects, then we can also use factory functions, but using constructors are a better idea.
    • With Factory methods also, in case we need to modify an object interface, we need to make changes at one place, like adding a new function to the object.
         function createEmp(firstName, lastName) {
             return {
                 firstName : firstName, 
                 lastName : lastName,
                 getFullName : function () {
                     return this.firstName+" "+ this.lastName;
                 }
             };
         }
         var prince = createEmp ("Prince", "Kapoor");
  • The way we have defined functions above, including defining in the constructor is not the best way as it stores function definition in the memory separately for each object.
    • If we define it using the prototype then function definition will be stored only once.
    • Functions defined for Date, String etc JavaScript objects are also defined in the same way.
Ex.      function Emp(firstname,lastname,id)        {
            this.firstname=firstname;
            this.lastname=lastname;
            this.ID=id;
        }
        Emp.prototype.getFullName = function ()
        {
            return this.firstname+" "+ this.lastname;
        }
  • By using apply(newObject) on function method, function can be executed as if it is part of another object.
        function Emp (firstname,lastname,id)
        {
            this.firstname=firstname;
            this.lastname=lastname;
            this.ID=id;
            this.getFullName = function (salutation)
            {
                return salutation+" "+this.firstname+" "+ this.lastname;
            }
        }

        function Person(firstname,lastname)
        {
            this.firstname=firstname;
            this.lastname=lastname;
        }

        var emp1 = new Emp("Prince", "Kapoor");
        var person1 = new Person ("Jai", "Bhaskar");
        document.write(emp1.getFullName.apply(person1, ["Mr."]));
  • In Apply we pass arguments as array and there is call() method, in which we pass arguments directly without any array.
        document.write(emp1.getFullName.call(person1, "Mr."));
  • Following is practical example of apply/call - using methods of Array on arguments object.
        Array.prototype.pop.apply(arguments);
  • Objects are very flexible and can be extended using prototype property to add more object properties or methods.
  • " prototype " extends object definition using its name, not instance name.
DOM:
  • Is an API for accessing and changing content, style document structure.
  • The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document. DOM is separated into 3 parts - Core DOM, XML DOM, HTML DOM. HTML DOM is standard object model for HTML. 
  • The HTML DOM is a standard for how to get, change, add, or delete HTML elements.
  • When a web page is loaded, the browser creates a Document Object Model of the page. The HTML DOM model is constructed as a tree of Objects. 
  • Window
    • Represents content area of the browser.
    • There are three types of dialog message communications: window.alert(), window.confirm(), and window.prompt()
    • window.open() is used to open a new window object.
    • window.moveTo()to move the current window.
    • window.document represents HTML document.
    • Object Type is DOMWindow.
    • Window object has two self-referential properties, window and self. Either of these global variable to refer directly to the Window object. Ex. self.close().
    • window.top refers to the top-most window in case of multiple frames.
    • window.self is mostly used in comparisons like: 
      • window.parent.frames[0] != window.self 
      • window.self != windpow.top
  • Navigator
    • Accesses browser program, version etc.
    • window.navigator.appCodeName,window.navigator.appName, window.navigator.platform, window.navigator.appVersion (in some cases appMinorVersion as well), window.navigator.userAgent, navigator.systemLanguage, navigator.cookieEnabled
    • navigator.javaEnabled() for checking if java is enabled.
  • Screen
    • Updates about physical environment in which browser is running, pixels height width etc.
    • Some key properties related to client screen are : window.screen.width, window.screen.height, window.innerWidth, window.innerHeight, window.screen.availWidth, window.screen.availHeight, and window.screen.colorDepth
  • History
    • For accessing browser history information.
    • window.history stores history information as an array.
    • history.back(), history.forward(), history.go() are key methods in history object.
  • Location
    • Maintains URL information of the page.
    • window.location object has 5 properties containing the components of full URL: location.href, location.protocol, location.host, location.pathname, location.hash
    • Assigning a new URL to the location property will cause the browser to load new page.
    • reload() method will cause the page to be reloaded.
    • replace() method replaces the history entry.
    • location.assign() method loads a new document.
      window.location.assign("http://www.princekapoor82.blogspot.com")
  • Document
    • Represents the HTML document.
    • Some key properties related to browser screen size are: document.body.clientWidth, document.body.clientHeight
    • document.title, document.URL(shows same information as location.href but not used for navigation), document.domain (similar to location.host), document.lastModified and document.referrer are some of the key properties.
    • document.write(), document.getElementById(), getElementByTagName(), getElementsByClassName() are some of the most frequently used methods.
    • write() vs CreateElement()
      • write cannot be used to add new components once the page has been loaded as write will remove the page content and then write its content.
      • write is mostly used during page load.
    • document object has properties (arrays) for child objects for forms, anchors, images, and links. Each of these objects is an array and contains items in the order in which they appear in the document. Please note: Images that are incorporated as part of the CSS Style are not part of images array, only images defines with <img> will constitute the array. These arrays are older ways of accessing the components, now getElementBy*() methods are supposed to be used.
    • form object has its own child elements for all the form elements.
    • Every form field has a form object that can be passed along to a function.
            onClick="validateDate(this.form)"

            function validateDate(form)
            {
                //Value of any field can be accessed using syntax:  
                form["StartDate"].value
            }
      • This approach of accessing data is same as getElementById() - It just makes code more readable.
      • Just like passing form object using this.form, you can pass form field object with this keyword. Ex
                onClick="validateDate(this)"
      • All the presentational DOM properties are contained within a parent style property, which is a child of the object. For ex. obj.style.textAlign 
    • To add/remove elements following methods can be used: document.createElement, document.createTextNode, <dom object reference>.appendChild, <parent dom object reference>.removeChild(<child dom object reference>);
Form Validation
  • Forms are used to collect information from websites checkboxes, textboxes, Buttons, dropdowns etc.
  • JavaScript can be used to validate data in HTML forms before sending off the content to a server.
Number & String
  • JavaScript numbers are stored as double precision floating point numbers.
  • parseInt("4 Apples") returns 4.
  • "10" == 10.0 returns true.
  • String (aNumber) converts number to string.
  • Number (aString) converts string to number.
  • "Prince" > "Kapoor" returns true because it evaluates based on ASCII.
  • To convert decimal to binary, octal, hexa-decimal, use toString method with appropriate base as parameter:
    var myNumber=16;
    document.write(myNumber.toString(16))   // prints 1
    document.write(myNumber.toString(8))    // prints 2
    document.write(myNumber.toString(2))    // returns 10000
  • Auto type casting of numbers to text happens when we use then in Alert (Alert expects text).
  • Text Strings must be enclosed within double quote, nested inner string should be enclosed within single qoute.
  • There is a discrepancy in floating point calculations in Java and JavaScript. Check the result of 15 * 81.66 or 0.7 * 5000 or 0.2 + 0.1.
  • Infinity is a special number, 1/0 is Infinity. (Infinity == var)
  • NaN - 1/"abc" is NaN, isNan()is used to check if parameter is a number or not.
  • Key Properties of Number - MAX_VALUE, MIN_VALUE, NEGATIVE_INFINITY, POSITIVE_INFINITY, NaN
  • Key Methods of Number - toExponential(), toFixed(), toPrecision(), toString(), valueOf()
  • String Key Property - length
  • String Key Methods - charAt(), charCodeAt(), concat(), fromCharCode(), indexOf(), lastIndexOf(), localeCompare(), match(), replace(), search(), slice(), split(), substr(), substring(), toLowerCase(), toUpperCase(), toString(), trim(), valueOf().
Image
  • Refers to images on the HTML screen (<img> tag).
  • Primarily used to pre-cache/pre-loading images based on some action/event. This helps in getting better response time.
  • To pre-load an image, we create a new Image() object in JavaScript and pass the URL of the image.
Array
  • There are three ways to create an array:
    1.
    var fruits = new Array();
   
fruits[0]="Orange";
    fruits[1]="Apple";
    fruits[2]="Banana";

    2.
    var fruits = new Array("Orange", "Apple", "Banana"); 

    3.
    var fruits = ["Orange", "Apple", "Banana"];
    var productList = []; // will create empty array.
  • Commonly used methods - length(), indexOf(), lastIndexOf(), concat().
  • Other operations methods - toString(), join(), slice(), splice(), reverse(), sort(), push(), pop(), shift(),
  • Array object has some interesting methods - every(), some(), filter(), forEach(), map()
    • These methods are passed callback function as parameter.
    • every() is equivalent of for all.
    • some() is for atleast one.
    • filter() creates a new array with items that match the criteria.
    • forEach() doesn't return anything, just executes the function on every element withing an array.
    • map() similar to forEach but returns the updated elements in a new array.
      • ex. arrayVar.every(arrayOfEvenNumbersTestFunc);
      • signature of callback function - 
        • arrayOfEvenNumbersTestFunc(value, index, array);
Operators
  • = = = and ! = = should be used to check equality and inequality. = =  and ! = may produce unexpected results. For Example - (true = = 1) will return true while (true = = = 1) will return false. = = = and ! = = doesn't perform type coercion.
  • Switch works fine for number, string, as well as boolean.
  • typeof operator can be used to get the type of the operand. Ex of types - "object", "boolean", "function", "number", "string", "undefined".
    • Ex. typeof var == "string".
  • instanceOf operator is used to if a variable is an instance of a Object
    • Ex. prince instanceOf Emp
Cookie
  • Distinct information delivered by web server to browser when they interact for the first time.
  • For basics of Cookie - refer to Key Internet Terms.
  • document.cookie is the cookie property.
DOM and CSS
  • All the presentational DOM properties are contained within a parent style property, which is a child of the object. For ex. obj.style.textAlign 
  • style.visibility is used to toggle visibility ("hidden"/"visible").
  • Variable declared without a value will have the value undefined. null and undefined are different.

Timers and Animation
  • There are following methods related to timer event
    • setInterval()
      • Executes a function repeatedly after a specified time interval.
      • myTimerVar=setInterval(<javascript function>,milliseconds);
    • setTimeOut()
      • Executes a function once after a specified time interval.
      • myTimerVar=setTimeOut(<javascript function>,milliseconds);
    • clearInterval()
      • Clears interval set with setInterval() to stop further executions.
      • clearInterval(myTimerVar);
    • clearTimeOut()
      • Same as clearInterval() to stop timer set with setTimeOut().
      • clearTimeOut(myTimerVar);

JavaScript Local Storage
  • Designed to hold key/value pairs.
  • Can only be accessed by JS window object.
    localStorage.userName = "Prince"; // stores userName.
    localStorage.setItem("LastName", "Kapoor"); // works same as above.
    localStorage.removeItem("userName"); // removes userName.
    localStorage.clear(); // clears all properties
  • Values stored in LocalStorage are always of type string.
  • JSON can also be used to store/retieve objects in LocalStorage.
  • LocalStorage is restricted to a domain.
Important Notes:
  • Alert() is technically method of windows object, it can also be called as windows.alert()
  • Script data gets refreshed on refreshing the web page.
  • To encode URI parameter (remove spaces and special characters), we have encodeURIComponent(). We normally encode for parameter and value.
  • obj.innerHTML !== "undefined" can be used to test if obj is a DOM object.
  • If "new" keyword is missing in object creation, then object properties defined with "this"  will be created in window object.
  • You can redeclare a variable, it'll not loose its value.
    var name="Prince";
    var name;
  • To prevent links from refreshing or loading another page, we can use the JavaScript void() function and pass a parameter of 0 (zero) and #.
    <a href="JavaScript:void(0);" onClick="alert('Testing Void(0)')">Click</a>
  • There is a special "for in" loop that can be used to list all the initialized properties and methods of an object (including DOM objects like windows etc). It can also be used for arrays (since arrays are also objects).
  • RegExp - Object to support regular expression.
  • The \n escape sequence is used to specify a newline character in the alert dialog text. 
  • KEYPRESS event doesn't capture modifier keys like Shift, Ctrl etc. KEYDOWN and KEYUP does capture.

Callback Functions

Inline JavaScript code and JavaScript functions can be assigned to any HTML event attribute, such as onClick, onLoad etc. 
<img id="update" src="updateImg.jpg" onClick="updateNavigation(3);">

Above approach mixes HTML and JavaScript, which intrudes structural nature of the HTML elements and increases maintainance and debugging efforts

We should keep the intergation of JavaScript and HTML to JavaScript itself. Following are some examples:

<body onload="initDetails();">
can be written in JavaScript as
windows.onload=initDetails; in the <HEAD> section.

<body onload="initDetails("read_only");"> 
can be written in JavaScript as
windows.onload = function(evt) { initDetails("read_only"); }

AJAX and JavaScript
  • AJAX can write script that request information from the server and then process and display that information on the page.
  • AJAX is not a technology but simply a new approach towards dynamic user interface combining other technologies.  
JavaScript Object Reference
  • JavaScript Object Reference will be helpful for coding in JavaScript. Reference will provide all the methods and properties available in an object.
Some Javascript examples:-

    Restricting users with what keys can be entered - 
    Check on key press event with the ascii code of the key pressed, if key is one of the restricted keys, then prevents default action.
 
    Implement Hot Keys - 
    event -> keyDown
    event.ctrlKey should be true.
    Compare ascii code to check if the key down is the key which we need to capture for hot keys.

Thursday, October 25, 2012

A Short Guide to CSS

Oracle Applications allows creation of Custom Look and Feel. All these custom look and feel creates a new CSS. We also define CSS property for many UI Widgets like OraDataText etc. All the existing skins defined in the profile option Oracle Applications Look and Feel also maintain their own style and thus their own css. You can find all the CSS at $OA_HTML/cabo/styles/cache in your file server. We'll learn basics of CSS here.

CSS

  • CSS stands for Cascading Style Sheets.
  • External Style Sheets are stored in CSS files.
  • Allows to separate HTML content from it’s style. Use your HTML file to arrange the content, and CSS for all of the presentation.
  • External CSS are shared and thus allows us to change Look and Feel of entire website by modifying one CSS file. 
  • CSS improves performance because style sheet only needs to be downloaded to client machine and then it's used from cache.
  • A nested element will inherit the properties assigned to the containing element.
  • In case if same style is mentioned multiple times in same CSS/HTML file, the effect is cascaded. Following are the rules:
    • If same style is defined multiple times in a file, then the one defined at the end will take preference in case if same property is defined.
    • Inline Style - Highest Priority
    • Internal Style Sheet - High Priority
    • External Style Sheet - Normal Priority
    • Browser Default - Low Priority
  • Divisions(<div>) are a block level (X)HTML element used to define sections of an (X)HTML file.
  • Spans(<span>) are very similar to divisions except they are an inline element versus a block level element.
  • width:40% will work with <div> and not with <span>, as div is block level while span is inline.
  Sample CSS Syntax

   selector {property:value;}
    p {color:red;text-align:center;}
    /* Below is syntax in more readable form */

    p
    {
        color:red;
        text-align:center;

    }
  • P is called Selector.
  • "color:red;" and "text-align:center;" are called declaration.
  • Every declaration ends with semi colon, and contains a property and value.
  • Every declaration group is surrounded by curly brackets.
  • /* .. */ is used for comments.
  • We can combine multiple selectors together while defining CSS
    h1, h2, h3, h4, h5, h6 
    {
        color: #009900;
        font-family: Georgia, sans-serif;
    }
      Inline Style
    • Uses HTML attribute style for this. 
      • <body style="background-color: #FF0000;">
        Internal Stylesheet
      • Placing CSS code directly into the <HEAD> section.
           <head>
               <title><title>
               <style type=”text/css”>

                   // CSS Content Goes Here
                   body
                   {
                       background-color:#d0e4fe;
                   }
               </style>
           </head>

      • <style> tag is used to define style information for a HTML document.
      • <style> tag can appear multiple times in a HTML document.
        External Stylesheet
      • Created as external file and linked to the HTML document.
      • We can link to the file externally by using either <link> or <style> with @import in the <head> section. 
           <link rel=”stylesheet” type=”text/css” href=“Path To stylesheet.css” />
           
           <style type="text/css">
               @import url("import3.css");
               p { color : #f00; }
           </style>

      • <link> is intended to link together your Web page with your style sheet.
      • <link> tag defines the relationship between a document and an external resource.
      • <link> element is an empty element, it contains attributes only.
      • <link> element can appear any number of times in <HEAD> section.
      • @import allows you to import one style sheet into another.
      • @import is a way of creating a style sheet within your document, and then importing additional rules into the document.
      • @import rule must always be the first in the document. Even comments shouldn't come before this.
      • <link> element gives better performance and more readable code compared to @import.

      Selector Type

        HTML Selector
      •  To redefine the general look for an entire HTML tag.
          p
          {

              font-family:verdana;
              text-align:left;
              color:blue;
          }


        Id Selector
      •  The id selector is used to specify a style for a single, unique element.
          #book
          {
              text-align:left;
              color:blue;
          }

          <div id="book">
              This is my first book. I wis
      h to write a technical book once...
          </div>

        Class Selector
      • Used to specify a style for a group of elements.
      • Can specify specific HTML elements which should be affected by a class.
          .red{color:red;} 
          p.red{color:red;}

        Context Dependent Selector or Nested Selector or  Decendant  Selector
      • Used to specify a style for a selector when its used in conjunction with another one.
           p b{color:red;font-weight:bold;}

           innerClassSelector {color:pink;}
           outerClassSelector {color:red;}
           .outerClassSelector .innerClassSelector{color:blue;}
      • When innerClassSelector is used inside outerClassSelector then this style will be applicable, else the default of innerClassSelector will be applicable.  innerClassSelector  needn't be the immediate child, but it should be in the same hierarchy.
      • Context dependent is specified by separating two classes with a space.
         Immediate Child Selector or child combinator selector
      • Similar to Context Dependent Selector but it looks for immediate child only.
      • It impacts only the first child.
          p > b{color:red;font-weight:bold;} 

          Adjacent Sibling Selector
        • It will style only the element that is immediately preceded by the former element.
             #MAN + p {color:green;}


          General Sibling Selector
        • It will style only the element that is preceded by the former element, may not be immediatly.
             #MAN ~ p {color:green;}

          Attribute Selector
        • Style HTML elements that have specific attributes.
            [title]{color:green;}

          Attribute and Value Selector
        • Below Styles all elements with title="Custom Product Branding":
            [title="Custom Product Branding"] {color:green;}
        • Below styles all elements with a title attribute that contains word "Hello":
            [title~=Hello] {color:green;}
          • It'll work for "Hello World", "World Hello" but will not work with "Hello-world".
          • [title~="Hello"] is same as [title~=Hello]
          • [title~="Hello World"] or  [title~="Hello "] will not select anything for Styling.
        • Below works if the attribute has hyphen ( - ) separated values:
            [title|=Hello] {color:green;}
          • It'll work for "Hello", "Hello-World" but will not work with "Hello World",  "World Hello" or "Hello!".
          • Mostly used for specifying languages.
        • Below works if the attribute contains word "Hello" anywhere in value:
            [title*=Hello] {color:green;}
        • Below works if the attribute begins with " http" anywhere in value:
            a[href^="http"] {color:green;}
        • Below works if the attribute ends with " .jpg" anywhere in value:
            a[href$=".jpg"] {color:green;}


        The CSS Box Model

        • Every element in web design is a rectangular box.
        • Calculate Dimensions as follows:

          Some Key Style Properties:

          text-decoration
          Set or remove decorations from text, mostly used to remove underlines from link
          h1 {text-decoration:overline;}
          h2 {text-decoration:line-through;}
          h3 {text-decoration:underline;}
          h4 {text-decoration:blink;}

          text-transform 
          To specify uppercase and lowercase letters in a text.
          p.uppercase {text-transform:uppercase;} <!-- All Upper case -->
          p.lowercase {text-transform:lowercase;} <!-- All Lower case -->
          p.capitalize {text-transform:capitalize;} <!-- Camel case -->

          text-indentation
          To specify the indentation of the first line of a text, like we have in paragraphs in book.

          list-style-image:url('listImage.gif');
          To specify image to be used for lists (instead of default square or circle etc)


          list-style-type:none;
          Will display list without any circle or square.
          display:inline; when used within the list, will display horizontal list.

          Display and Visibility
          .hide{visibility:hidden;}
          .hide{display:none;}
          visibility:hidden hides an element, but it will still take up the same space as before.
          display:none doesn't take up any space.

          :first-child Pseudo-class
          Styles a specified element that is the first child of another element.
          p:first-child{color:blue;} 

          Style the first p element
          .outerClass > .innerClass:first-child
          Styles first .innerClass element in all .outerClass elements.
          .outerClass:first-child .innerClass
          Styles all .innerClass elements in first .outerClass element.



          :first-letter and :first-line Pseudo-element
          The :first-letter selector is used to add a style to the first letter of the specified selector.
          :first-line Styles the first line of text in a block level element.
          p:first-letter, div:first-letter {font-size:medium; color:#ff0000;}
          p:first-line, div:first-line {font-size:medium; color: #00ff00;}
          p.intro:first-line, div:first-line {font-size:medium; color: #00ff00;}

          opacity
          Create a transparent images and text with CSS.
          img
          {
          opacity:0.5;
          filter:alpha(opacity=50); /* For IE8 and earlier */
          }



          @media Rule
          Media Types allow you to specify how documents will be presented in different media.
          @media screen
            {
            p {color:red;}
            }
          @media print
            {
            p {color:green;}
            }

          Tips:
          • Adding a border on hover makes images look coming out on mouse hover in Page.

          Few New Features in CSS3:

          • Border-radius
          • @font-face
          • Box-shadow 
          • 2D Transforms
          • Multi-Column Layout
          • Multiple Backgrounds
          • Opacity

          Tuesday, October 16, 2012

          A short guide on HTML

          We all are working on Web Developments, and underneath all webpages is good old HTML. It helps to understand HTML a bit. I realized it more while working on new OAF CLAF. The challenge was to match the new Oracle Apps skin with the corporate website built on .net. Along with HTML, knowledge of UIX, CSS, and JAVASCRIPT is required for CLAF. Hope to cover it all, starting with HTML.
          • Every web page you create must include the <HTML>, <HEAD>, <TITLE> and <BODY> tags.
          • <TITLE> is used to identify the page on Bookmarks and Favorites list.
          • The web addresses contained in a web page are of two types - Absolute (complete address) and relative (address of the resource from current page).
          • File Extension (.JSP, .jsp) and (.HTM, .htm) could refer to same file on windows server but different on unix server. Its better to be uniform in the use of extension.
          • HTML to download a file:
               <A HREF="Prince_Kapoor2012.docx"> Click here to download my resume</A>

          • While testing your application it'll be a nice idea to test your pages in less color and less resolution mode.
          • There are actually two ways of making text display as bold: <b> and <Strong> and Italics: <I>, <EM>. Purists prefer to use <Strong> and <EM> because they imply that the text should receive special emphasis, rather than dictating exactly how that effect should be achieved. <B> and <I> remain the more popular of the two options.
          •  Every form must begin with a form tag, which can be located anywhere in the body of the HTML document. The <Form> tag normally has two attributes, METHOD and ACTION:
               <form action="mailto:princekapoor82@gmail.com" method="post">
          •  <!--    --> indicates comments.
          • The format of color code is #RRGGBB, where rr, gg and bb are two digit hexadecimal values for the red, green and blue.
          • Please be aware that different computer monitors may display colors in very different hues. A shade of blue on one monitor may look purple in another. Sticking to named colors is preferred choice.
          • Spacer component of OAF and empty space in others is created as a small transparent images used in Img tag with width and height attributes. (/OA_HTML/cabo/images/t.gif)
          • An HTML table is an orderly arrangement of text and/or graphics into vertical columns and rows.
            • OAF Table, AdvanceTable and TableLayout both are rendered as HTML table.
            • Even the MessageTextInput is rendered as an HTML table with prompts as separate column (right aligned) and values as separate (left aligned).
            • Closing </TD> is optional, since one cell of the table must end before the next one begins.
            • Tags used in one cell are not carried over to other cells and tags from outside the table don't apply within the table.
          • A Search Engine is an automated computer program that looks in a database index for pages that contain specific words and phrases. 
          • A Robot (also called a Spider) is an automated computer program that spends all day looking at the web pages all over the internet and building a database of the contents of all the pages it visits. They work for building the database of the Search Engine.
          • The <meta> tag provides metadata about the HTML document. Metadata will not be displayed on the page, but will be machine parsable.
            • Meta elements are typically used to specify page description, keywords, author of the document, last modified, and other metadata.
            • The metadata can be used by browsers (how to display content or reload page), search engines (keywords), or other web services.
            • It is put in <Head> portion of a document.
          <META NAME ="description" CONTENT="Prince Kapoor OAF Blog.">
          <META NAME="keywords" CONTENT="OAF, ADF, Oracle Apps Framework, Oracle Apps Technical, Oracle Application Framework">

          The first tag gives search engine accurate information about your web page and second slightly increases page's ranking on the result based of the keywords.

          NAME -  Specifies a name for the metadata. Values for this attribute are application-name, author, description, generator, keywords.

          Following is usually the first line in the <Head> section:
            • HTML 4.01: <meta http-equiv="content-type" content="text/html; charset=UTF-8">
            • HTML5: <meta charset="UTF-8">
          http-equiv - Provides an HTTP header for the information/value of the content attribute. Values for this attribute are content-type, default-style, refresh.
          content - Gives the value associated with the http-equiv or name attribute.
          charset - Specifies the character encoding for the HTML document. 

          Following will refresh the document every 30 secs
          <meta http-equiv="refresh" content="30">
          • Frames
            • Way of arranging and presenting several web pages at once.
            • Rectangular region within the browser window that displays a page, alongside other pages in other frames.
          • Frameset
            • Frameset document is an HTML page that instructs the Web Browser to split its window into multiple frames and specifies which web page should be displayed in each frame.
          • IFrame
            • The Iframe (Inline Frame - Inline with the data on text/graphics on the page) is set up as a rigid size window frame that scrolls along with the rest of the page and it can exist without having a frameset defined. 
            • Designed to insert interactive applications in Web pages.
            • Frameset is not required for IFrame.
            • One can alter an IFrame’s sections without requiring the user to reload the surrounding page.
            • PPRs in OAF are implemented using IFRAMEs
          • In the HTML source of any OAF page, you'll see <div> and <span> used very frequently with the CSS. The difference between them is - div is a block element and comes with line breaks, span is inline.
          • DHTML is Dynamic HTML.
            • DHTML is a way for you to change the way your pages look. You can instantly change the color of a page with the click of the mouse or without the click of a mouse. You can cause things to happen just by moving the mouse around the page.
            • Combination of HTML and Client side scripting like Java Script.
          • Title attribute is used for showing tip text/extra information. Following are some example:
          <a href="http://princekapoor82.blogspot.com" title="OAF Blog">Prince Kapoor Blog</a>
          <abbr title="Oracle Applications Self Service Framework">OAF</abbr>
          <p title="Oracle Applications Self Service Framework Training">OAF Training</p>

          •  <IMG> tag should contain alt, width and height attribute. Text in alt will be displayed if image can't be displayed. width and height attribute make the page render faster on the browser.
          • <!DOCTYPE>
            • The <!DOCTYPE> declaration must be the very first thing in your HTML document, before the <html> tag.
            • The <!DOCTYPE> declaration is not an HTML tag; it is an instruction to the web browser about what version of HTML the page is written in.
            •  Following are the examples:
               For HTML 5:-
              <!DOCTYPE html>

              For HTML 4.1 Strict:-
              <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

              HTML 4.01 Transitional:-
              <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
            •  DOCTYPE indicates we are specifying the document type.
            •  HTML means HTML is the root(first) element in your page.
            •  PUBLIC means standard is publicly available.
            •  "-//W3C//DTD HTML 4.01 Transitional//EN" indicates the exact version of that HTML.
            •  "http://www.w3.org/TR/html4/loose.dtd" indicates the file that identifies the particular standard. 
          • http://princekapoor82.blogspot.com or  http://princekapoor82.blogspot.com/ will cause the server to look for a default file. The URL will change to http://princekapoor82.blogspot.com/index.html or http://princekapoor82.blogspot.com/default.htm depending on the web server.