JavaScript Quiz #7

Assume that we have the following short JavaScript code:

<script>
    var result = typeof("Hello" instanceof String);
    alert(result); //What is the output of the alert? 
	
    result = typeof typeof("Hello" instanceof String);
    alert(result); //What is the output of the alert? 
	
    result = typeof typeof typeof("Hello" instanceof String);
    alert(result); //What is the output of the alert? 	
</script>

What is the output of each alert?

Know the complete answer

Resolving the virtual keyboard popup issue in Android 2.x browsers

One of the alarming issues of the Android 2.x browsers is that virtual keyboard sometimes becomes open even if the cursor is not focused on an editable field.
This symptom can be extended to a degree that the virtual keyboard can be still open in views other than the one that initially shows the keyboard.

After spending hours in trying to figure out a solution to this problem, I tried the following solutions and none of them worked with me:
1. Disabling the input elements in the form temperaroly.
2. Setting the input elements in the form to read-only temporarily.
3. Blurring the current focused editable field does not also work.

The only way that works with me is to send an enter key to one of the text fields in the form (or to any hidden field) after 1000 milliseconds before performing the transition to any other views, this can be done in Dojo mobile as follows:

window.setTimeout(function() {

    registry.byId("[your dojo/mobile/textbox id]")._onInput({ charOrCode: keys.ENTER });

}, 1000);

If you have a better solution for this issue, let me know.

JavaScript Quiz #5

This quiz covers some of the JavaScript operators in order to explain they can work together inside expressions. Assume that we have the following JavaScript code:

var object1 = {
    valueOf: function () {
	return 10;
    },
    toString: function () {
	return "object1";
    }
};

var object2 = {
    valueOf: function () {
	return 20;
    },
    toString: function () {
	return "object2";
    }
};

var object3 = {
    valueOf: function () {
	return 30;
    },
    toString: function () {
	return "object3";
    }
};

var result = (object2, object1, object3) + object1 +-- object1; 
alert(result);

What is the output of the alert?

Read the complete answer

JavaScript Quiz #4

Understanding JavaScript by example is useful for absorbing the different concepts of the language quickly. In this post, I will illustrate a JavaScript quiz in order to understand how JavaScript operators work together. Assume that we have the following JavaScript code:

var object1 = {
    valueOf: function () {
        return 1;
    },
    toString: function () {
        return "object1";
    }
};

var object2 = {
    valueOf: function () {
        return 2;
    },
    toString: function () {
        return "object2";
    }
};

alert((object2 > object1 +-- object1) + true); //What is the output of the alert?

What is the output of the alert?

Read the complete answer

JavaScript Quiz #3

Understanding JavaScript by example is useful for absorbing the different concepts of the language quickly. In this post, I will illustrate a quick JavaScript Quiz to understand how JavaScript (+) operator works. Assume that we have the following JavaScript code:

var object1 = {
    someVar: 2,
    someName: "object1",
    valueOf: function () {	
        return this.someVar;
    },
    toString: function () {	
        return this.someName;
    }
};

var result = "I equal " + object1;

alert(result); //What is the output of the alert?

What is the output of the alert?

Read the complete answer

Resetting dojox.mobile.ScrollableView to top

ScrollableView is a container widget which represents an entire mobile device screen, and has a touch scrolling capability. Sometimes, you may need to reset ScrollableView to the top or to any position in the mobile screen.
In order to achieve this requirement, you need to use its scrollTo() API, for example, scrolling to top can be done by setting x and y to zero as follows:

require(["dojox/mobile/parser", "dijit/registry", ..., "dojo/domReady!"], function(parser, registry) {
	//...
	var view = registry.byId("someViewID");
	view.scrollTo({x:0 ,y: 0});
	//...
});

Following this approach, you can scroll ScrollableView to any position you like by specifying a suitable x and y values.

JavaScript Quiz #2

Now, it is the time for the second JavaScript quiz.

Assume that we have the following JavaScript code:

var someVar = "1";
var someObject = {
	someVar: 2,
	someMethod: function () {
		var someVar = 3;
		var _this = this;
		
		setTimeout(function() {
			var result = _this.someVar + this.someVar;
			
			alert(result); //What is the value of result here?
			
			if (result > 20) {
				+result--;
			} else {
				+result++;
			}
			
			alert(result); //What is the value of result here?
			
		}, 10);		
	}
};

someObject.someMethod();

The question is what is the output in each alert and Why?
.
.
.
.
.
.
.
.
.
.
.
.
.
In order to understand how this JavaScript example will work, we should know the following:
1. How the JavaScript “this” keyword works.
2. How the JavaScript operators work.

I illustrated in details how the JavaScript “this” keyword works here, in summary, “this” evaluates to the object on which the method was invoked. This means that _this.someVar inside the setIimeout will be evaluated to 2.

It is important to understand how the + Arithmetic operator work, in the following line:

var result = _this.someVar + this.someVar;

The value of result in this line will be evaluated to: 2 + “1” = “21”. This is because the + Arithmetic JavaScript operator always favors String which means that if you have a numeric + String, the numeric operand will be converted to String and the result of the + Arithmetic operator will be a simple String concatenation.

Then coming to the next line:

result > 20

Here there is a comparison between both String and a numeric, unlike the + Arithmetic operator, the JavaScript Relational operators favor numeric, which means that result will be converted to integer so the comparison will be 21 > 20 which will be evaluated to true.

Finally in the following line:

+result--;

The + unary operator can be used to convert its operand to integer, however, it has no effect here as the evaluation of the expression the — post-increment operator is executed before it which will convert result to integer and decrement it by 1.

This is the explanation why the alerts will produce the following results in order:
1. 21
2. 20

This is all about this quiz. Stay tuned for the next one soon!

>>Edited in 01 April 2013.

Getting Yahoo! Weather from JavaScript ONLY

Getting weather information in mashup applications is a very common task. As you may know, Yahoo! thankfully provided a REST API that can be used in order to get weather information using location’s zip code.
In order to invoke the Yahoo! weather REST API from JavaScript client, you can either create an XHR request that talks with a local server proxy which deals with the Yahoo! weather REST API (in order to avoid the security exception of cross-domain Ajax requests on the JavaScript client) or to use JSONP which is supported by the Yahoo! Query Language. In this post, the second approach will be illustrated because it does not require any server side work.

Dojo has a "dojo/request/script" module that can handle interactions with JSONP endpoints as follows:

require(["dojo/request/script"], function(script){
  script.get(URL, {
    jsonp: "callback",
    preventCache: true,
    timeout: 3000
  }).then(function(response) {
    // Do something with the response data
  }, function(error) {
    // Handle the error
  });
});

script object has a get API that has two parameters:
1. JSONP Service URL.
2. JSON object with optional parameters. Optional parameters can be:
a. jsonp: The name of the JSONP query parameter.
b. preventCache for cache prevention.
c. timeout: The number of milliseconds to wait for the response. If this time passes the request is canceled and the promise rejected.

For the complete list of optional parameters, check Dojo documentation here.

This is all about what you need to know about this API. Now, let’s see how to retrieve the weather information of an example place (New Era – Michigan) which has the following zip code 49446.

var errorMessage = "Unable to get weather information.";

var zipcode = "49446"; //New Era - Michigan

var query = "q=" + escape(
		  "select item from weather.forecast where location") + 
		  "=\"" + zipcode + "\"";

var endPointURL = "http://query.yahooapis.com/v1/public/yql?" + query  + 
		  "&format=json";


script.get(endPointURL, {
	jsonp: "callback",
	preventCache: true,
	timeout: 3000
}).then(function(response) {
	try {
		document.getElementById("someDivID").innerHTML = response.query.results.channel.item.description;
	} catch (exception) {
		alert(errorMessage);
	}
}, function(error) {
	alert(errorMessage + " Make sure that your device is connected to the internet.");
	console.log(error); 
});

endPointURL includes the Yahoo! REST service URL with the needed parameters and the request timeout parameter is set to 3 seconds.

Once the JSON response is retrieved successfully from the server, it will look like the following:

dojo.io.script.jsonp_dojoIoScript2._jsonpCallback({"query":{"count":1,"created":"2013-03-18T02:34:06Z","lang":"en-US","results":{"channel":{"item":{"title":"Conditions for New Era, MI at 9:33 pm EDT","lat":"43.56","long":"-86.35","link":"http://us.rd.yahoo.com/dailynews/rss/weather/New_Era__MI/*http://weather.yahoo.com/forecast/USMI0597_f.html","pubDate":"Sun, 17 Mar 2013 9:33 pm EDT","condition":{"code":"33","date":"Sun, 17 Mar 2013 9:33 pm EDT","temp":"24","text":"Fair"},"description":"\n<img src=\"http://l.yimg.com/a/i/us/we/52/33.gif\"/><br />\n<b>Current Conditions:</b><br />\nFair, 24 F<BR />\n<BR /><b>Forecast:</b><BR />\nSun - Mostly Clear. High: 29 Low: 22<br />\nMon - PM Snow. High: 37 Low: 23<br />\n<br />\n<a href=\"http://us.rd.yahoo.com/dailynews/rss/weather/New_Era__MI/*http://weather.yahoo.com/forecast/USMI0597_f.html\">Full Forecast at Yahoo! Weather</a><BR/><BR/>\n(provided by <a href=\"http://www.weather.com\" >The Weather Channel</a>)<br/>\n","forecast":[{"code":"33","date":"17 Mar 2013","day":"Sun","high":"29","low":"22","text":"Mostly Clear"},{"code":"16","date":"18 Mar 2013","day":"Mon","high":"37","low":"23","text":"PM Snow"}],"guid":{"isPermaLink":"false","content":"USMI0597_2013_03_18_7_00_EDT"}}}}}});

This is why using the response.query.results.channel.item.description long expression will get the required weather information from the returned service response.

JavaScript Quiz #1

Having quizzes from time to time is very important in order to refresh our information. This is why I decided to post JavaScript quizzes in order to have a better understanding of JavaScript.

Assume that we have the following JavaScript code:

var someVar = 1;
var someObject = {
	someVar: 2,
	someMethod: function () {
		var someVar = 3;
		
		alert(this.someVar); //What is the result ???
		
		setTimeout(function(){
			alert(this.someVar); //What is the result ???
		}, 10);		
	}
};

someObject.someMethod();

The question is what is the output in each alert and Why?
.
.
.
.
.
.
.
.
.
.
.
.
.
In order to understand how this JavaScript example will work, we should know how the JavaScript “this” keyword works. It is important to know that within a body of JavaScript method, “this” evaluates to the object on which the method was invoked.

This mean in the “this.someVar” expression of the first alert, “this” will be evaluated to someObject object on which someMethod method was invoked, which will result in 2 (the value set in line 3).

In the “this.someVar” expression of the second alert, “this” will be evaluated to Window global object because of the window.setTimeout, which will result in 1 (the value set in line 1).

This is all about this quiz. Stay tuned for the next one soon!

Resolving the z-index problem in Android 2.x Browser

One of the alarming issues of the Android 2.x Browser is that it does not respect the z-index of input elements, this issue is described here in details:
http://code.google.com/p/android/issues/detail?id=6721.

This issue can actually be very blocker to you if your mobile web application contains many openers that utilize the z-index CSS property in order to appear on the top of the active mobile view. This is because when the application’s opener is active and due to this bug, you can find the underlying mobile view input elements highlighted (focused) on the top of the opener as shown in the figure below.
BUG

In order to resolve this issue, I applied the following solution that works with me:
1. When a new opener is opened:
All of the *relevant* underlying input elements inside the view must be disabled. Doing this fix will disable the keyboard interaction with the underlying input elements and in the same time will not allow these input elements to be *focused*.

2. When the opener is closed:
All of the disabled input elements in the first step can be re-enabled again.

The solution looks complex, however, it can help if you have a similar situation.