Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Tuesday, October 18, 2016

JQuery 101.

JQuery Basic Syntax

  • $("a")
  • $('a')
  • $(document)
  • $("#elementID")
  • $(".className")

Load the event in JQuery
$(document).ready (function () {
    ...
} );

By ID
$(document).ready (function () {
    // getElementById("linkOne")
    $("#linkOne").css("color", "#abacad");
} );

By class
$(document).ready (function () {
    $(".className").css("color", "#abacad");} );

By Type
$(document).ready (function () {
    $('div').css("color", "#abacad");} );
    $('a').css("color", "#abacad");} );

By Hierarchy
$(document).ready (function () {
    $("div a").css("color", "#abacad");} );
    $("div > p").css("color", "#abacad");} );
    $("#linkOne a").css("color", "#abacad");} );
    $("p:nth-child(3)").css("color", "#abacad");} );
} );

By Position/Index
$(document).ready (function () {
    $("p:first").css("color", "#abacad");} );
    $("p:last").css("color", "#abacad");} );
    // To select second <p> element
    $("p")[1].css("color", "#abacad");} );
    // To select third <p> element or third paragraph
    $("p:eq(3)").css("color", "#abacad");} );
    // To select even number <p> element
    $("p:even").css("color", "#abacad");} );
} );

By Attribute
$(document).ready (function () {
    // Select all images that have "alt" attribute
    $("img[alt]")[1].css("color", "#abacad");} );
    // Select images that have "alt" attribute set to text
    $("img[alt='text']")[1].css("color", "#abacad");} );
    // Select images that have "alt" attribute set to "text"
    $('img[alt="text"]')[1].css("color", "#abacad");} );
    // or
    $("img[alt=\"text\"]")[1].css("color", "#abacad");} );
} );


AJAX 101.

Using XMLHttpRequest
function readyAJAX() {
    try {
        return new XMLHttpRequest();
    } catch (e) {
        try {
            return new ActiveXObject("Msxml2.XMLHTTP");
        } catch(e) {
            try {
                return new ActiveXObject("Microsoft.XMLHTTP");
            } catch(e) {
                return "New Browser Required.";
            }
        }
    }
}

Sending an AJAX Request
var requestObj = readyAJAX();
var url = "http://www.amazon.com";
requestObj.open("GET", url, true) ; // asynchronous non-blocking request

// Actual send with this line
requestObj.send();


Processing an AJAX Response
// a synchronous call and response retrieval
var requestObj = readyAJAX();
var url = "http://www.amazon.com";
requestObj.open("GET", url, false);
requestObj.send();
if (requestObj.status == 200) {
    alert(requestObj.responseText);
} else {
    alert(requestObj.statusText);

}
// an Asynchronous call and response retrieval
var requestObj = readyAJAX();
var url = "http://www.amazon.com";
requestObj.open("GET", url, true);
requestObj.send();

// Use onreadystatechange to trigger code 
// that checks the event's readyState
// readyState : 0 - uninitialized, open but yet has to be called
//              1 - open but yet to be sent
//              2 - sent
//              3 - receiving, the response has yet to be ready
//              4 - loaded, response fully received

requestObj.onreadystatechange = function () {
    if (requestObj.readyState == 4) {
        if (requestObj.status == 200) {
            alert(requestObj.responseText);
        } else {
            alert(requestObj.statusText);
        }
    }
}

Processing an XML Response
var requestObj = readyAJAX();
var url = "http://www.amazon.com";
requestObj.open("GET", url, false);
requestObj.send();
if (requestObj.status == 200) {
    var xmldocument = requestObj.responseXML;
    alert(xmldocument.getElementsByTagName("isbn")[0].childNodes[0].nodeValue);
} else {
    alert(requestObj.statusText);
}

Processing an JSON Response
var requestObj = readyAJAX();
var url = "http://www.amazon.com";
requestObj.open("GET", url, false);
requestObj.send();
if (requestObj.status == 200) {
    var jsondocument = eval('(' + requestObj.responseText + ')');
    alert(jsondocument.book.title);
} else {
    alert(requestObj.statusText);
}

// JSON data looks like this:
{
"book":
    {
   "title": "bookname",
   "isbn" : "938874637383"
    }
}

Processing Headers
  • HTTP HEAD method returns just the response headers from the server.
    • GET method returns the headers and the body
    • Useful to determine whether a resource has been updated or changed.
    • Useful header: Expires, indicating the client should request a refreshed copy from server.
  • Use "getAllResponseHeaders()" method of "XMLHttpRequest" object to obtain only the response headers
    • requestObj.getAllResponseHeaders();
<script type = "text/javascript">
function readyAJAX() { ... }

var requestObj = readyAJAX();
var url = "http: //www.domain.com/";
requestObj.open ("HEAD", url, true);
requestObj.send();
requestObj.onreadystatechange = function () {
   if (requestObj.readyState == 4) {
      if (requestObj.status == 200) {
         alert (requestObj.getAllResponseHeaders());
      } else {
         alert (requestObj.statusText);
      }
   }
}
</script>

Using POST method
  • Parameters sent with POST request are contained int he body of the request rather than in the URL, as in GET request
    • Less likely to be seen by those trying to find ways into your application.
  • Supports larger requests.
    • Amount or size of a GET request are often limited by some servers to a certain amount of characters.
    • Amount or size of a POST request can be limited as well but are almost always much greater.
  • Requires an additional header to be set within the request, using "setRequestHeader()" method.
    • requestObj.setRequestHeader (header, value);

// AJAX requests using GET
// The URL looks like:
// http://www.domain.com/books/javascriptsbs/isbn.php?isbn=9876543212345

//AJAX request using POST
requestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

// Example
<script type = "text/javascript">
function readyAJAX() { ... }

var requestObj = readyAJAX();
var url = "http://www.domain.com/books/javascriptsbs/post.php";
var params = "num1=2&num2=2";
requestObj.open("POST", url, true);
requestObj.setRequestHeader ("Content-type", "application/x-www-form-urlencoded");
requestObj.send(params);
requestObj.onreadystatechange = function () {
   if (requestObj.readyState == 4) {
      if (requestObj.status == 200) {
         alert (requestObj.responseText);
      } else {
         alert (requestObj.statusText);
      }
   }
}
</script>

AJAX and jQuery

  • List of Parameters
    • type
    • url
    • dataType
    • success
    • error
    • timeout
    • data (to the server) : 
      • data: (key1=value1 & key2=value2)
      • data: {key3=value3, key4=value4}
    • Async vs cache
  • Functions
    • .load()
    • .post()
    • .get()
    • .ajax()
    • .getJSON() - same as calling .ajax() with parameter dataType set to 'json'
      • using parameter to call GET, POST, or set time-out
      • $.ajax ({ parameter: value });

$.ajax ({
   url: "testajax.aspx",
   success: function (data) {
      alert ("Successful load");
   }
)}
<script type = "text/javascript">
$(document).ready (function () {

$.ajax( {
   type: "GET",
   url: "json.php",
   dataType: "json",
   success: showStates,
   error: errorFunction,
   timeout: 5000,
   data: "state=CA"
});

// The function showStates creates a list and adds it to a form's <SELECT>
// drop-down box.
function showStates (data, status) {
   $.each (data, function (item) {
      $("#states").append ("<div>" + data[item] + "</div>");
   } );
}
function errorFunction ( xhr, statusMessage, httpErrorCode ) {
   alert ("An error has occurred: " + statusMessage);
}

});
</script>

Saturday, October 15, 2016

DOM 101.

Node Types
  1. Element_node
  2. Attribute_node
  3. Text_node
  4. Cdata_section_node
  5. Entity_reference_node
  6. Entity_node
  7. Processing_Instruction_node
  8. Comment_node
  9. Document_node
  10. Document_type_node
  11. Document_fragment_node
  12. Notation_node

Node Relationships

  • childNodes - a NodeList ordered by  position / index.
    • firstChild
    • lastChild
    • nth-child
  • parentNode
  • nextSibling or previousSibling
  • Ancestors or Descendants

Window Objects and Its Children (DOM as a tree)

  • Window
    • Self
    • Document
      • html
        • head
          • title
        • body
          • p -> innerText
          • p -> LinkText -> a -> www/URL
    • Navigator
    • Screen
    • Forms
    • History
    • Location

Window Object Methods and Properties
  • Methods
    • addEventListener()
    • attachEvent()
    • blur()
    • focus()
    • close()
    • detachEvent()
    • removeEventListener()
    • open()
    • print()
    • Moving and Resizing
      • moveBy()
      • moveTo()
      • resizeBy()
      • resizeTo()
    • Timers
      • clearInterval()
      • clearTimeout()
      • setInterval()
      • setTmeout()
    • Get Information of the Screen
      • availHeight
      • availWidth
      • colorDepth
      • height
      • width
  • Properties
    • closed
    • defaultStatus
    • name
    • opener
    • parent
    • status
    • top

Example
alert ("Available Height: " + screen.availHeight);
alert ("Total Height: " + screen.height);
alert ("Available Width: " + screen.availWidth);
alert ("Total Width: " + screen.width);

// navigator object
var body = document.getElementsByTagName ("body")[0];
for (var prop in navigator) {
   var elem = document.createElement("p");
   var text = document.createTextNode (prop + ": " + navigator[prop]);
   elem.appendChild(text);
   body.appendChild(elem);
}




Sunday, October 9, 2016

OOP Programming Terms.


CRUD versus REST

CRUD means the basic operations to be done in a data repository. You directly handle records or data objects; apart from these operations, the records are passive entities. Typically it's just database tables and records. It is a simple term that was abbreviated because it's a common feature in many applications, and it's easier to say CRUD. It describes the 4 basic operations you can perform on data (or a resource). Create, Read, Update, Delete.

REST, on the other hand, operates on resource representations, each one identified by an URL. These are typically not data objects, but complex objects abstractions. It is more of a named practice just like AJAX but not a technology in itself. It encourages use of capabilities that have long been inherent in the HTTP protocol, but seldom used. When you have a URL (Uniform Resource Locator) and you point your browser to it by the address line, you're sending an HTTP request. Each HTTP request contains information that the server can use to know which HTTP response to send back to the client that issued the request.

Each request contains a URL, so the server knows which resource you want to access, but it can also contain a method. A method describes what to do with that resource.

But this "method" concept wasn't used very often.

Usually, people would just link to pages via the GET method, and issue any type of updates (deletions, insertions, updates) via the POST method.

And because of that you couldn't treat one resource (URL) as a true resource in itself. You had to have separate URLs for deletion, insertion or update of the same resource.

For example, a resource can be a user's comment. That means not only a record in a 'comment' table, but also its relationships with the 'user' resource, the post that comments, maybe another comment that it answers.

Operating on the comment isn't a primitive database operation, it can have significant side effects, like firing an alert to the original poster, or recalculating some gamelike 'points', or updating some 'followers stream'.

Also, a resource representation includes hypertext (check the HATEOAS principle), allowing the designer to express relationships between resources, or guiding the REST client in an operation's workflow.

In short, CRUD is a set primitive operations (mostly for databases and static data storages), while REST is a very-high-level API style (mostly for webservices and other 'live' systems).

a single URL describes a single resource. A single post is a single resource. With REST you treat resources the way they were meant to be treated. You're telling the server which resource you want to handle, and how to handle it.

There are many other features to "RESTful architecture", which you can read about in Wikipedia, other articles or books, if you're interested. There isn't a whole lot more to CRUD itself, on the other hand.


Example
http://...com/posts/create- POST request  -> Goes to posts.create() method in the server
http://...com/posts/1/show- GET request  -> Goes to posts.show(1) method in the server
http://...com/posts/1/delete - POST request  -> Goes to posts.delete(1) method in the server
http://...com/posts/1/edit- POST request  -> Goes to posts.edit(1) method in the server
With REST, you create forms that are smarter because they use other HTTP methods aside of POST, and program your server to be able to distinguish between methods, not only URLS. So for example:
http://...com/posts - POST request  -> Goes to posts.create() method in the server
http://...com/posts/1 - GET request  -> Goes to posts.show(1) method in the server
http://...com/posts/1 - DELETE request  -> Goes to posts.delete(1) method in the server
http://...com/posts/1 - PUT request  -> Goes to posts.edit(1) method in the server

CDN (Content Distribution Network)
  • Several companies, including Google and Microsoft, allow you to link to jQuery, and some other common libraries, and get that file directly from their servers.
  • This is more reliable and speedier.
  • Spreading the requests across different servers can improve performance.
  • Caching benefits - shared sites got cached on the client machine.
  • Remove "http:" to avoid complaints of encryption or not.
Example
// Linking to Google CDN
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js">
</script>
// remove http:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js">
</script>

Abstract Factory pattern vs Factory Method pattern

Abstract Factory vs. Factory Method

The methods of an Abstract Factory are implemented as Factory Methods. Both the Abstract Factory Pattern and the Factory Method Pattern decouples the client system from the actual implementation classes through the abstract types and factories. The Factory Method creates objects through inheritance where the Abstract Factory creates objects through composition.

The Abstract Factory Pattern consists of an AbstractFactory, ConcreteFactory, AbstractProduct, ConcreteProduct and Client.

How to implement

The Abstract Factory Pattern can be implemented using the Factory Method Pattern, Prototype Pattern or the Singleton Pattern. The ConcreteFactory object can be implemented as a Singleton as only one instance of the ConcreteFactory object is needed.

Factory Method pattern is a simplified version of Abstract Factory pattern. Factory Method pattern is responsible of creating products that belong to one family, while Abstract Factory pattern deals with multiple families of products.

Factory Method uses interfaces and abstract classes to decouple the client from the generator class and the resulting products. Abstract Factory has a generator that is a container for several factory methods, along with interfaces decoupling the client from the generator and the products.

When to Use the Factory Method Pattern

Use the Factory Method pattern when there is a need to decouple a client from a particular product that it uses. Use the Factory Method to relieve a client of responsibility for creating and configuring instances of a product.

When to Use the Abstract Factory Pattern

Use the Abstract Factory pattern when clients must be decoupled from product classes. Especially useful for program configuration and modification. The Abstract Factory pattern can also enforce constraints about which classes must be used with others. It may be a lot of work to make new concrete factories.


Saturday, October 8, 2016

JavaScript Good Practices.

Variable and Function Style
  • variables and functions : use camelCase
    • var score;
    • var myDate;
    • function loanCalculator() { ... }
  • Yahoo, Google, Java, DOM, JQuery
  • Always use block - even if one line
  • Define functions before calling them to make them readable (though you don't have to)
  • Open curly braces on the same line
  • Always use semicolons to end a statement
  • Always use var when declaring a variable 
  • JavaScript Minifier
  • JavaScript Checker/Linter
  • JQuery

Brace Style
// 
// JavaScript's own ability to insert what it thinks are missing 
// semicolons on lines that don't have them

// Place the opening curly brace at the same line of keyword, if, while
// and always use block as possible
if (x) {
} else {
}

// compare to Pascal or Allman style, Avoid.
if (x)
{
}
else
{
}

Note: Check Yahoo, Google, Mozilla for "javascript style guidelines"

Useful Links



JavaScript and CSS.

Setting Inline Styles
  • Always set the property as a string.
  • myElement.style.color = "#ff0000";
  • myElement.style.left = "40px";
  • myElement.style.width = "230px";
  • myElement.style.fontWeight = "bold";               // notice, it's not font-weight, '-' is subtract in js
  • myElement.style.backgroundColor = "#123";    // notice, it's not background-color
  • myElement.style.backgroundRepeat = "repeat-x";

Setting the Class
  • 'class' is reserved keyword in js.
  • myElement.className = "someCSSclass";
  • myElement.className = "";

Example
// In myStyle.css
// .example {
// color: #fff;
// }

// JavaScript
document.getElementById("mainContent").className = "example";


var currPos = 0;
var intervalHandle;
function beginAnimate() {
    document.getElementById("join").style.position = "absolute";
    document.getElementById("join").style.left = "0px";
    document.getElementById("join").style.top = "100px";
    intervalHandle = setInterval (animate, 60);
}

function animate() {
    currPos += 6;
    document.getElementById("join").style.left = currPos + "px";
    if (currPos > 800) {
        clearInterval (intervalHandle);
        document.getElementById("join").style.position = "";
        document.getElementById("join").style.left = "";
        document.getElementById("join").style.top = "";
    }
}

window.onload = function() {
    settimeout (beginAnimate, 4000);
}


JavaScript Forms.

  • field values
  • field events
  • form events (submit)

Example
<form id="frmContact" name="frmContact" method="post" action="thanks.htm">
     <fieldset id="personalInfo">
        <legend><strong>Personal Information</strong></legend>
        <p>
            <label for="name">Name</label>
            <input name="name" type="text" class="text" id="name" 
                       tabindex="100">
        </p>
        <p>
            <label for="email">Email</label>
            <input name="email" type="text" class="text" id="email" 
                          tabindex="110">
        </p>
        <p>
            <label for="phone">Phone</label>
            <input name="phone" type="text" class="text" id="phone" 
                          tabindex="130">
        </p>
        <p>
            <label for="address">Address</label>
            <input name="address" type="text" class="text" id="address" 
                          tabindex="150">
        </p>
...
document.forms.frmContact
document.forms.frmContact.name

Text Fields
  • main property 
    • myTextField.value 
  • main events 
    • onfocus, onblur, onchange, onkeypress, onkeydown, onkeyup

Checkboxes and Radio Buttons
  • main property
    • myCheckBox.checked (true or false)
  • main events
    • onclick, onchange

Select Lists
  • main property
    • mySelect.type (select-one or select-multiple)
    • mySelect.select-one
      • mySelect.selectedIndex
    • mySelect.select-multiple
      • mySelect.options[x].selected (true or false)
  • main events
    • onchange
Form Events
  • main event
    • onsubmit (can return false to validate field values)
function prepareEventHandlers () {
    document.getelementById ("frmContact').onsubmit = function() {
    // prevent a form from submitting if no email
    if (document.getelementById ("email").value == "") {
        document.getElementById ("errorMessage").innerHTML = 
                  "Please provide an email address!";
        // to Stop the form from submitting
        return false;
    } else {
        // reset and allow the form to submit
        document.getElementById ("errorMessage").innerHTML = "";
        return true;
    }
}

window.onload = function () {
    prepare EventHandlers ();
}


Example : expand check fields when clicked "brochures"
function preparePage() {
    document.getElementById("brochures").onclick) {
        if (document.getElementById("brochures").checked) {
            document.getElementById("tourSelection").style.display = "block";
        } else {
            document.getElementById("tourSelection").style.display = "none";
        }
    }
    document.getElementById("tourSelection").style.display = "none";
}

window.onload = function() {
    preparePage();
}


Timer Summary.


JavaScript
  • setInterval  (<function>,  5000);   // unit is milliseconds
  • setTimeout (<function>,  5000);
  • clearInterval (handler);
  • clearTimeout (handler);

Example
var myImage = document.getelementById("mainImage");
var imageArray = ["_images/overlook.jpg", "_images/tree.pg",...]
var imageIndex = 0;

function changeImage() {
    myImage.setAttribute ("src", imageArray[imageIndex]);
    imageIndex++;
    if (imageIndex >= imageArray.length) {
        imageIndex = 0;
    }
}

var intervalHandle = setInterval (changeImage, 5000);
myImage.onclick = function() {
    clearInterval (intervalHandler);
}

Java


JavaScript Events.


There are three methods in JavaScript in listening and handling events:

  • onload
  • onclick
  • onmouseover
  • onblur
  • onfocus


METHOD 1
<button onclick="alert('Hello, world!');">
    Run Some JavaScript
</button>

METHOD 2 : Use Element Name and Event Name
// element.event = ...
// ex. window.onload 
// ex. namefield.onblur

myelement.onclick = function () {
    // your event handler code
    // ...
};
// The semi-colon because the 
// whole thing is a statement! (Not because of function)


METHOD 3 : Add Event Listener
// Benefit: flexible, one event for multiple listensers, dynamic
// Drawback : different, not portable across browsers

document.addEventListener ('click', myFunction, false);
//                             event , function to run 

document.addEventListener ('click', anotherFunc, false);
// dynamically add and remove listeners on the same event
document.removeEventListener ('click', anotherFunc, false);
// For IE8
// document.attachEvent ('onclick', myFunction);

// Cross-Browser Add Event Helper Methods
function addCrossBrowserEventListener (elementName, eventName,
functionName) {
    // does the addEventListener function exist?
    if (elementName.addEventListener) {
        // yes - use it
        elementName.addEventListener (eventName, functionName, false);
        return true;
    } else {
        // otherwise use attachEvent
        elementName.attachEventListener 
            ("on" + eventName, functionName, false);
        return true;
    }
}
// or use JQuery


Note:
If the line of javascript, <script src="script.js"></script>, is placed in the <head></head> section, use 'window.onload' to activate the function as soon as the page is loading.

// place script.js at end of <body></body>
var myImage = document.getElementById ("mainImage");
myImage.onclick = function() {
    alert ("Image Clicked!");
}

// Place script.js in <head></head>
function prepareEventHandlers () {
    var myImage = document.getElementById ("mainImage");
    myImage.onclick = function() {
        alert ("Image Clicked!");
    }
}

// Use window.onload to make sure the elements exist before 
// javascript function is called
window.onload = function() {
    prepareEventHandlers ();
}
// window.onload should only be used once for each page, 
// the last one stands.


// in html, input email and name:
<p>
   <label for="email">Email:</label>
   <input type="text" value="your email" name = "email" 
        id="email" tabindex="20" />
</p>

// in javascript:
var emailField = document.getelementById("email");

emailField.onfocus = function() {
    if (emailfield.value == "your email") {
        emailField.value = "";
    }
};

emailField.onblur = function() {
    if ( emailField.value == "") {
        emailfield.value = "your email";
    }
}


Tuesday, August 30, 2016

Node.js 101!


Basics:
  • Node.js is single thread
  • Node.js is asynchronous (non-blocking)

Useful Links:

JavaScript 101!

Basics
    General:
    • It's case sensitive
    • End each statement with ;
    • Very forgiving if you forget to close the statement with ;
    • Not sensitive to white spaces (except in strings "" or line breaks.
    • /* comments */ or // comments and the rest
    • If you need it to create page, put in <head> otherwise, put it before </body>
    • var abc, _xxx, $yyy; var year=2020;  // JS a weakly typed language
    Control Flows:
    • if ( condition ) { statements }

Keywords
  • alert
  • console.log
  • true, false
  • var

Find ...
    var a = document.getElementById ("mainTitle");
    var b = document.getElementsByTagName ("li");
    var b = document.getElementsByClassName ("description");
    
    document.getElementById ("mainTitle").className = "highlight";
    
    // JQuery Methods and Alias
    jQuery(".discription").addClass("highlight");
    $("myclass").addClass("highlight");
    $("li").addclass("hightlight");
    $("p:contains('packages')").hide(4000);
    $("p").fadeOut(4000);
    
    jQuery("#maintitle").removeClass("highlight");
    jQuery("li:last").toggleClass("highlight");
    
    $("#pageID").click (function() {
        $("#pageID").text ("You clicked text!");
    });
    $("h2").click (function() {
        $(this).text ("You clicked here!");
    });
    $("p").click (function() {
        $(this).fadeOut (3000);
    });
    
    // Page load events - same as window.onload()
    // But don't have to worry about calling it multiple times
    $(document).ready(function () {
        $("#pageID").text ("DOM fully loaded.");
    });
    $(document).ready(function () {
        $("h1").css ("color", "red");
    });
    
    

    Example
    <script>
       console.log ("Download Git, Firebug and enable Console!")
    
       var myvar = 1000;
    
       newvar = 555; // skip "var" is okay but it is not a good practice.
    
       var lineone = "this is line one.";
    
       var just_the_num = lineone.slice(8);
    
       console.log(just_the_num);
    
       console.log(`Now we only have this part: ${just_the_num}`); 
    
    </script>
    
    

    Only in Node.js:
    
       // var path = require("path");
    
       // console.log(__filename);  // full pathname and file name
    
       // console.log(__dirname); // full pathname to current directory
    
       // alert(` remove the path: ${path.basename(__filename)}`);  
    // just the file name
    
    
    
    Or put the code in another file "greeting.js", and
    
    
    
    <script src="greeting.js" type="text/javascript">
    
        // alert (greeting.firstline); // won't work
    
    </script>
    
    

    Useful Links:

    Books: