DCSIMG
June 2009 - Posts - Pini Dayan

Pini Dayan

The best thing about a boolean is even if you are wrong, you are only off by a bit.

June 2009 - Posts

IE 8 New way to select objects using CSS selectors

When we wish to set some styling rules to a certain group on html controls on a given page - the proper way to do it is to use CSS selectors. CSS selectors come in many ways , You can write simple selector, complex selectors and even group them together.

Basically Selectors are the patterns that determine which style rules apply to elements of the document tree.

Lets see some sample:

Type element selectors: Will find all the div elements and set their font size to 22px

div{
     font-size:22px;
   }
Class Selector: Will find all the p elements that has a class attribute of "wrpa" 
and set their some properties.

p.wrap

  {
     text-align: center;
     color: red;                
  }
ID selector: Will find all the elements that with the Wrap as ID.
#WRAP
{
  background-color: silver;               
  border-color: gray;
}    

Descendent Selector: will find all the elements that are immediate or not immediate child of ...

h1 em{ color: red}  

Now what is we wish to use this selectors syntax and find those elements using JavaScript.

Well It is now possible using IE 8 JavaScript new features.

The document object has now new 2 functions :

1. document.querySelectorAll(selectorStr)

2. document.querySelector(selectorStr)

 

  For example, Lets say I have the following HTML:

<div id="div1">aaa</div>
<div class="SomeClass">bbb</div>
<div class="SomeClass">ccc</div>
<input type=button id="btnTest" onclick="GoSelectors();" value="Go selectors">

And the following JavaScript code:

function GoSelectors()
{ 
   var oDiv = document.querySelector("#div1");
   var oDivs = document.querySelectorAll("div.SomeClass");
   alert(oDiv.id);
   alert(oDivs.length);
}

The first js statement will return the div object with the id "div1" and the second statement will return all the div object with the given class name.

To read more:http://msdn.microsoft.com/en-us/library/cc288326(VS.85).aspx

IE 8 new Feature for working with JSON

When I am lecturing "Microsoft Ajax" and I need to show some Ajax sample that uses JSON I explain to my students that they need to download some js files and place them in the web site in order for them to work with JSON in the client side.

When I am referring to working with JSON  I usually mean 3 things:

1. Converting a string into a JSON object.

2. Converting an existing object into it's JSON string representation.

3. Converting an XML string into JSON object.

So for the first 2 I usually show the parse and stringify functions available in the free file to download from here: json2.js

At it turns out IE 8 has already a support for working with JSON. It contains a global object named "JSON" which has 2 methods. From msdn:

"An intrinsic object that provides methods to convert JScript values to and from the JavaScript Object Notation (JSON) format"

1. The JSON.stringify will convert an object (JavaScript object) into a JSON string:

var obj = new Object();
obj.x = 5;
obj.y = 6;

alert(JSON.stringify(obj));

will produce  the string   "{ 'x': 5, 'y': 6}"

2. The JSON.parse will convert a string into a JSON object.

var str = JSON.stringify(obj);
var obj2 = JSON.parse(str);
alert(obj2.x);

Some notes:

1. The JSON is available when the page is loaded (The engine is loaded).

2. You cannot create this JSON object using the new operator.

image

 

IE 8 Connectivity Enhancements

If you ask any .NET developer what is the number of http requests you can send to a given server at once - he will answer 2. He will be even more sure if he wrote some ajax pages or even worked with Microsoft Ajax.

Well as it turns out this answer is not correct. and especially not true in case of IE 8. As it turns out , when we are using IE 8 , rather its an HTTP 1.0 or HTTP 1.1 request we can now use  6 concurrent connections to the same server.

Here is a summary table from the msdn site:

image

The limitation was because of the 2 historical reasons:

1. At the time it was decided this was the limitation in other browsers.

2. At the time it was decided the Internet was not as fast as today . Today of chores we have high-bandwidth connections.

For more details: AJAX - Connectivity Enhancements in Internet Explorer 8

IE 8 JavaScript Improvements

Hi All, I happen to read the release notes of Microsoft IE 8 here and was amazed from something I have discovered.

The story begins from a devolvement request I received a few days ago. The request was to check if there is a Internet connection every X second ( 30 seconds actually). Well At the beginning what I did was very simple : I injected a JavaScript block by using the base page of the project. This JavaScript code calls some functions that uses window.setInterval function to run the connectivity check every 30 seconds:

var nSetTimeOutInterval;
var oXmlhttpForConnectionChecking;
function StartInternetConnection() {
    nSetTimeOutInterval = window.setInterval("CheckInternetConnection();", 
     parseInt(GetConnectionTimeOut(), 10) * 1000);
}

As you can see, I am keeping my interval id (handler) as a global variable so that I can cancel it I want to. In addition I am using a web.config file to specify the time interval.

Now we need to actually check if the Internet is "on":

function CheckInternetConnection() {   
    oXmlhttp = new XMLHttpRequest();    
    var sURL = GetTestConnectionURL();
    oXmlhttp.timeout = 5000;
    oXmlhttp.ontimeout = TimeoutFired;
    oXmlhttp.open("GET", sURL, true);
    oXmlhttp.onreadystatechange = GotAnswer;
    oXmlhttp.send(null);
}

 

The GetTestConnectionURL function will return the url for an empty page in the web site (to reduce traffic).

The call will be Async of obviously so we will not stuck the UI. We also have to set a timeout so that the request will not hang too much. (This timeout property only exists in XMLHttpRequest object). Now all that is left is to check that the http status code is 200.

 

function GotAnswer() {
    // if xmlhttp shows "loaded"
    if (oXmlhttp.readyState == 4) {
        //if "OK"
        if (oXmlhttp.status == 200) {
            //Do nothing....                       
        }
        else {
            alert("Note:The internet connection is lost...");
            window.clearInterval(nSetTimeOutInterval);
        }
    }
}
 

Well today I found a better way. IE 8 added a new property to the window.navigator object - window.navigator.onLine. Amazing!!!
This property is has  boolean value of true if we are online and false if we are not.

Try to alert this value when your network cable is connected and when it is not....

This is not all! As a bonus we can even register our page to 2 new events: onoffline and ononline.

These events will be called when the onLine property changes from true to false and from false to true.

JavaScript tip: How to send unknown number of arguments to a function

During my last lecture in the course: "Advanced JavaScript" I was asked by a student an interesting question. The question was, How do I create a function that can receive an unknown number of arguments. The hand was raised when we learned the Array construction function options. When you create an Array in JavaScript you have many option of creating it:
<script>
       var
arr = new Array(); //Creates an empty array.
      
var arrObj = Array(); //Creates an empty array.
      
var arr = new Array("One", "Two", "Three");
       var arrObj = Array(54, 32, 77, 76);
       var arr = new Array(5);    //Can you guess what will be the length of this array ? :-)

       var arrObj = Array(5);
   </script>

Notice the second and third options. This constructor function accepts an unknown of argument that will initialize the array and determine it's initial size.

OK, So what if we wish to create our own function that can get an unknown number if args? just like C# has params option.

Well the answer is very simple. Every JavaScript function is an object. This object has properties (From it's prototype). One of these properties is "arguments". The arguments property consists of an array of all the arguments passed to a function.

Here is a simple example of how to create a method named "Add" that can receive an unknown number of args:

<script>
      function Add()
      {
        var nSum = 0
        for (var i = 0; i < arguments.length; i++) {
            nSum = nSum + arguments[i]
        }
        return nSum;
    }
</script>
Enjoy!