Javascript

...now browsing by category

 

Javascript method chaining example

Monday, November 10th, 2014

Javascript method chaining is basically a chain of method calls that instead of call multiple times, just get called once and “chained” to one single object instance – the singleton pattern here. Below are some working samples I created after reading a good reference at http://coursesweb.net/javascript/chain-methods-javascript-object; to try it out, just copy the codes below and paste it to a notepad and then render in any browser.

<html>
<body>
<div id="d1">
<h3>Method chaining example</h3>

<a href="javascript:getArea();">Get Area</a>
<br />
<a href="javascript:getPerimeter();">Get Perimeter</a>
</div>

</body>
</html>

<script type="text/javascript">
var rec=new Rectangule();

function getArea()
{
//alert(rec.Area(3,4)); //this is without chaining
alert(rec.SetParam(3,4).Area()); //chaining

}

function getPerimeter()
{

//alert(rec.Perimeter(3,4));
//method chaining
alert(rec.SetParam(3,4).Perimeter());

}
function Rectangule()
{
var a=0,b=0;

this.SetParam=function(a1,b1){
a=a1;b=b1;
return this; //this is what makes chaining possible.
}

this.Area=function(){
return a*b;

}

this.Perimeter=function(){
return 2*(a+b);

}

}

</script>

Javascript closure example

Tuesday, October 7th, 2014

<html>
<body>
<div id=”d1″>
<h3>Closure example</h3>

<a href=”javascript:runCounter();”>Run Counter</a>
</div>

</body>
</html>

<script type=”text/javascript”>
function runCounter()
{
var add=(function(){
var counter=0;
return function(){return counter+=1;} //need return for nested function
//var result=(function(){return counter+=1;})(); //this does not work
//alert(result);
})();

alert(add());
alert(add());
alert(add());

}
</script>

One glitch to watch for while migrating jQuery lib from 1.3.2 to 1.7.1

Friday, September 14th, 2012

A recent deployment of my production website involved upgrading jquery library from jquery-1.3.2.min.js to jquery-1.7.1.min.js. Everything seemed to be fine except one place that was out of place – a customized div message box that initially displayed correctly next to mouse pointer now moved to the upper left corner of the screen.

What happened was that somehow 1.7.1 no longer supports $().mousemove() without passing in a definitive element identifier in the $(). Before the upgrade (jquery1.3.2.min.js), I used this code to capture the mouse position:

 var mouseX; var mouseY; $().mousemove(function(e){ mouseX=e.pageX; mouseY=e.pageY; }); 

And the mouseX and mouseY would have legit values. But these values were lost when I upgraded to jquery.1.7.1.min.js, if I kept the same code.

As it turned out, I needed to put a definitive html element id, either an id for a div or a table, in the $(). The new code that works the same as before the upgrade now should look like this:

var mouseX;
var mouseY;
$("#divid1").mousemove(function(e)
{
mouseX=e.pageX;
mouseY=e.pageY;

});

Now my popup box would display correctly to where I have my mouse over some item with this code below:


function showHints(msgDivId, msg,visible)
{
//alert("mouse position: " + mouseX + "," + mouseY);
var ch=$("#" + msgDivId);
ch.html(msg);
ch.addClass('hoverPopup');
ch.css({
left:mouseX+10,
top:mouseY-10
});
if (visible && msg.length>0)
ch.show();
else
ch.hide();

}

Inject custom message to warn user from closing browser window

Tuesday, June 26th, 2012

In a recent project, I needed to inject a custom message to warn user not to simply close a browser window; they might be doing some online course work and have not sent their course data back to server, and accidentally close down the browser. We didn’t want that to happen. At the beginning, I attempted the window.unload() event, and placed custom message there; but that, strangely, only works in IE7, but not in IE8,9, or recent versions of Chrome.

Naturally, I resolved to jQuery and found that this posting here at http://www.mkyong.com/jquery/how-to-stop-a-page-from-exit-or-unload-with-jquery/ was most useful. The author of this posting gave a good example and even embedded a demo. The thing I wanted to stress is that you must place the javascript code that handles the “beforeunload” event inside the body tag. At first, I placed in in <head> section and the event handler did not fire.

For jQuary library, I used direct reference from Google hosted solution, instead of referencing to local resource. Click hereto see what it looks like with different browsers and view the source. Try to enter a custom message to the text box on the lower part of the page, then try to close your browser. You will see the message you type in the box get added to the browser’s warning message while you try to close the page. For FireFox, it behaves quite differently – the custom message never got displayed and the default message differs from IE and Chorme, as shown in the image.

Return JSON data synchronously using jQuery.ajax()

Friday, September 10th, 2010

Normally, I would have used .getJSON(remotePageUrl,data,function(json){

//process JSON data here, for example

//if (json.length>0)

{

alert(json[0].Name);

}

});

 

to get a JSON object returned from the remotePageUrl that processes my request asynchronously and send back a JSON format string like ‘{“Name”:”steve”,”ID”: “1234”}’

But today, I found out that the .getJSON() cannot be set to process data request synchronously. In order to send data to remotePageUrl and return result synchronously (reason for this was because I had a jQuery dialog to be populated with data returned from this call before the dialog was displayed; first I used $.getJSON(), the dialog showed up before the data was processed on server side and returned), I needed to use $.ajax(). Here is the ajax call that actually worked to serve my purpose well:

 

var dataUrl = “<%=root%>/ajax/AsyncEventDataHandler.aspx”;

var userid; var eventTypeId; var userEventDesc=”;

var responseText = $.ajax({

url: dataUrl,

type: ‘GET’,

dataType: ‘JSON’,

//dataType: ‘text’,

contentType: ‘application/json’,

data: “UserCalendarID=” + userCalendarID,

async: false,

success: function (response) {

 

 

var data=$.parseJSON(response);

userid = data.UserID;

eventTypeId = data.EventTypeID;

userEventDesc = data.UserEventDesc;

 

 

},

 

error: function (msg) { alert(“error: ” + msg); }

 

}).responseText;

Here the response inside the function() is the same as $.ajax(….).responseText, and it should have a proper JSON string format or the jQuery.parseJSON() function will fail. The correct format example: ‘{“UserID”:”1211″,”EventTypeID”:”1″,”UserEventDesc”:”meeting”}’. I tried to put single quote around the field name and it did not go through $.parseJSON(). For example, this will not be parsed: “{‘UserID': ‘1211’,’EventTypeID':’1′,’UserEventDesc':’meeting’}”.

For that I attributed to this article at jQuery api site at: http://api.jquery.com/jQuery.parseJSON/. Otherwise, I would probably wasted more time in figuring out why the parsing was failing.

 

Using Google-hosted jQuery library

Monday, August 9th, 2010

Nice thing about using Google hosted jQuery is that I could call jQuery lib from anywhere and take advantage of versioning  and compression maintenance work done by Google. According to some source, the better caching provided by Google actually speed up the loading of the javascripts.

For example, below is a dialog box that uses jQuery UI hosted at Google. Click on the link to see it in action.

Show Dialog

Source code:

<link href=”http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css” rel=”stylesheet” type=”text/css” />
<script src=”http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js”></script>
<script src=”http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js”></script>
<script type=”text/javascript”>
function showDialog() {

$(“#dialog”).dialog({autoOpen:false, modal:true,buttons: {OK:function(){$(this).dialog(‘close’); }}});

$(“#dialog”).dialog(‘open’);

}

</script>

<div id=”dialog” title=”hello dialog”></div>