Author Archives: Hammad Tariq - Page 2

Current Airline Situation: Where is the Volcanic Ash Cloud now?

The biggest news in April 2010 that the air-space over UK and several other European countries was closed due to the fears that volcanic ash cloud from Eyjafjallajokull volcano in Iceland can damage the airplanes, I got this news one fine Monday morning while going towards tube escalators that due to volcanic ash the airports are closed and passengers are advised to contact their airlines before leaving home. I never thought what could be the consequences of it, apparently the airspace remained closed for several days, caused airline industry millions of dollar damage and misery to the passengers who were caught oversees with no funds in their wallets.

Eyjafjallajokull Volcanic Ash Cloud

Well that is nature, I being a big supporter of nature and most of the time in-peace with whatever nature do with us, it always has a reason. Several of my friends marked it as the end of earth as there were couple of earth quacks in the world around the eruption as well but sadly what they forgot was when millions of years ago when earth was in it’s early stages,  the seismic activity was far frequent and was at a much larger scale. In fact today we make movies about the Ice Age is coming due to global warming etc. while we had an Ice Age before when likes of were not even on earth!  The only difference now is, we see every bit of this live on our television screens and our airspace get closed because of this and then in our comfortable routine lives, we think, oh that’s bizarre, no for me it’s not!

Well this disruption which this ash cloud is causing and will continue to cause for several days, holiday industry will be the one who will suffer most  this summer. I know this because I planned to go out traveling on next bank holiday weekend which is from 29th May to 31st May. Due to this cloud, I looked at euro-star website, even before good 3 weeks the prices were already near £86 one way for Paris. I had been to Paris last summer, that’s a wonderful city but can’t give that much money to just to be there again. After considering several options, I am now booked with Ryan Air for Stockholm. The ticket was cheap but now I am not sure whether I will be able to fly or should I have a plan B ready in case of disruption.
As I am now tracking this ash cloud from several days (since I booked my ticket), I now know that it all depends on the winds, the big ocean currents which rule the weather of earth. This ash cloud will be there for several months but it will keep on swaying itself. As UK is nearest to Iceland, the most disruptions will be caused here but again depends on the direction of wind. Stockholm again is not very far away.
As the ash cloud today again caused some airports to shut down for couple of days in south-east England which has the most busiest airports in UK, the MET office UK which is also acting as the main outlet to hand-out ash cloud predictions have decided to list next 5-days predictions of cloud direction on their website instead of only 18 hours.
So here are the charts for next 5 day prediction of volcanic ash cloud on MET Office UK Website. If you are like me, going out soon, booked your ticket and now praying that this cloud do not come on your way, you need to keep an eye on the cloud, we have the science to predict but do not have the science to control it. It’s nature at work!

UPDATE:  There is no ash cloud from several years in a row but British Govt. or European Union has done little in recent years to stop this happening again. London Heathrow is a major travel hub with hundreds of flights going from UK to Anywhere, if they stop, a major financial hub of the world get stuck in the middle. London to New York is major travel route for busy city executives, it’s important more than ever to devise protocols to keep planes operating in all sorts of environments!

PIA: Pakistan International Airlines Pilot refused to fly from New York to Lahore

I would like to clarify it first that I am a very loyal customer of PIA (Pakistan International Airlines), the reasons of this I will explain later in this blog. First, I would like to talk about a tiny news appeared in the 2nd May, 2010 Jang Newspaper which reported that pilot of PIA flight PK-712 refused to take the plane back to Lahore from New York because of non-availability of the rest cabin for the crew. Here is the snapshot of that news:

Snapshot of news appeared in Jang May 2nd, 2010

According to the newspaper, the flight leaves New York at 5:30am and in alternate crew, there is always a pilot and first officer which rest for first 8 hours of flight and take charge of the plane for the next 8 hours. I have checked the flight duration on PIA’s website and it is almost 16 hours. The requirement of alternate cock-pit crew is compulsory due to international safety standards.

PALPA (Pakistan Airline Pilots’ Association) took this matter to the international authority about 5 days before this incident. Newspaper further told that the administration of Airline is thinking of operating the flight with a stop in Manchester on the way-back, so the cock-pit crew can be changed at Manchester Airport.

Later that day, I read on the Newspaper’s latest news that PIA has denied the fact that the pilot has refused to fly any flight and this flight will leave New York at its due time.

As a frequent air traveler and a avid fan of Discovery’s Air Crash Investigations, I got worried after reading this news. This was a very small news in the inside pages but I know exactly how this can be the cause of a very big news if a crash happened just due to this. National flag carrier has 9 Boeing-777 airplanes including Boeing-777LR and holds the record for longest commercial jet flight in aviation industry. The airplanes are made for long range flights specifically and were bought to cater for Toronto, Chicago and New York flights basically. However, while it gives you a great flexibility of operating at longer routes, it gives you a great responsibility of handling the flight safely without any break on the way.

The New York flight takes a break in Manchester on it’s way from Lahore to New York while on the return it come as a direct flight and takes about 16 hours. I am sure that while ordering an airline can ask for any modifications in the plane seating-wise and I am sure the original design would have a rest cabin included with the airplane as the airplane was intended for long-haul flights and I am sure again that PIA would have asked to remove the cabin to increase seating capacity.

PIA-777ER at runway

What makes me worried is a tired pilot who remain seated for first 8 hours of the flight and then he would be flying the plane back to the safety of airport for the next 8 hours. Everyone in airline industry know what a tired pilot flying an aircraft means, a flight in danger of a clash if anything goes wrong, obviously if the pilot is tired, his capability of handling potential hazards would be very low than a fresh pilot. We have seen many airliners crashing in bad weather, low visibility areas or in case of engine failures because either the pilot or first officer was tired and they missed the steps to handle the hazard.

Recently, another news in the same newspaper I read was about the maintenance of these multi-million dollar airplanes (Boeing-777) because the hanger for these airplanes were not made at the home of PIA (Pakistan International Airlines), the Karachi Airport. As of this reason, PIA is already not maintaining these airplanes properly and at times the flights are getting delayed due to security reasons in flying a faulty aircraft.

PIA has recently reported a surge in it’s operating profit which remained about Rs.5 billion in the past year. However, if you are not maintaining the safety standards and stretching your crew to get profit, that is a very risky bet, if in-case an aircraft got crashed due to these reasons, the airline would not only lose it’s multi-million dollar investment in the aircraft but also hundreds of lives along with a bad name for the airline.

I am a frequent flyer with PIA and always choose this airline whenever I go back  home. The reasons behind why I always choose this airline are not that it is a great airline to fly with or they are very hospitable (steward never reply the call, I always have to go to the kitchen myself to drink water), the PIA tickets are not cheap if compared to other airline’s fares and they are not that great in flying according to schedule (flights are often late). The reasons are, number one you get a direct flight from London to Lahore, you are in Pakistan in 8 hours, you do not need to change planes etc. If you take Emirates or Etihad or any other airline, obviously they stop at their home airports en-route. Second reason is much emotional, when you are traveling with PIA, the time when you get to your departure gate, you feel yourself as you are in Pakistan because the passengers and crew will be of your country and that makes you more happy, while coming back until you don’t leave the exit gate of heathrow airport, you again feel yourself at home, within your own people. Other than this, in-flight meals are just OK, the floors are dirty and because mostly it’s Boeing-777 which operates at heathrow route as well, the LCD screens for entertainment on the back of seats are starting to pose problems as well. It never happened with me yet but the passengers sitting beside me, normally their in-flight entertainment system will not work and they will keep on complaining and stewards will keep on saying that I am looking at the problem and nothing will happen. Obviously the airline is not taking care of it’s assets and it’s name.

PIA is our national flag carrier and despite of the fact that I am concerned with the safety of it’s airplanes and other factors, I will keep on flying with this airline as for the reasons I stated above. However, the airline itself need to give itself some fact-check and see what can happen if they keep on ignoring it’s crew and the maintenance of it’s aircraft.

Update 24/02/2014: PIA is the only airline now which flies direct from UK to Pakistan. Airblue was in competition and was even trying to expand it’s presence by offering Manchester to Lahore flight alongside existing Manchester to Islamabad route but reportedly due to some problems with availability of aircrafts, Airblue decided to pull out from the UK market. As a result, PIA seats are selling quickly due to ageing immigrant community who only want to travel direct. There are still some ways to get cheap flights to Pakistan through PIA and other airlines such as Emirates, Qatar, Etihad and Turkish airline but if you want to fly direct, it would be better to book your flight at least 3 months in advance.

Pakistan’s WAPDA and WAPDA’s website both got hacked!

Get Pakistan Breaking News app for Android now!

I recently came back from Pakistan and as most Pakistanis I was concerned with frequent power blackouts there. These power blackouts are known as load shedding in Pakistan as WAPDA (Water and Power Development Authority) and it’s controlling authority PEPCO (Pakistan Electric Power Company) try to manage the load across the power grids so none of them get blown off. The result of short fall of more than 5000MW daily is that public is sitting idle without electricity for more than 12 hours daily.

As a professional in web services I want to know every thing from the Web and on times I felt the urge to log-on to WAPDA’s website to get to know what is actually happening. What I would expect from the authority, is that, their website would have a map of Pakistan, which would get updated live through AJAX or it could be a Java applet which show you how many MWs are currently available, how many of them are actually getting distributed, how much are the line losses and how much is the demand. Then on the map additionally, you could see which areas are out of electricity at the particular moment.

I know that WAPDA will not do this ever until the political and bureaucratic structure of the authority get changed. The reason behind is, WAPDA has the capacity to generate more than 19,000MW a day through it’s own hydel power plants and through other IPP (Independent Power Producer) plants across the country. WAPDA hasn’t deliberately paid the payments to IPPs which in turn hasn’t paid fuel supplying companies, so those power plants are actually not running on their full strength and the power at the end available in the country is around 12,000MW a day.

Let’s take that in a bigger picture, when the government could get a loan of more than 7 billion dollar from international agencies with in a time frame of 2 years, it has taken too much loan from inside the company as well, why it couldn’t just pay back the IPPs debt which is around 100 billion Pakistani rupee (approximately 1.2 billion dollars) and due to only this reason, the whole country is in trouble including the industry and commercial sector and only this reason is causing a halt to growth and pushing the government to take more loans.

Yes, the last point is the answer, this is the game to pressurize the people of Pakistan so that they do not see toward the so-called war on terror game at the borders of Pakistan, secondly so that Pakistan should take more and more loans so like today, when international agencies ask something from us and we say we would not do that, they will say OK we will not release any more funds for you and as we will be down to our knees, we will do as “they” say.

Now on the corruption side of current “democratic” government of Pakistan, which country on earth would install more power plants when you have enough capacity available already and about 40% of it is not in use because of fuel supply? Well, the country’s name is Pakistan. In lieu of this scenario obviously Mr. 10% would like to have a bigger share out of his presidency, so what we are seeing is the Minister of Power saying again and again that it is due to the non-availability of power generation capacity (when 40% is idle) and then Pakistan is getting rental power plants which are expensive to get and install and more off they run on same kind of fuel which you are already not supplying to current power generators. The only purpose seems here to get kickbacks from those rental power plant operators.

This is a well known fact and every Pakistani is aware of that, anyway I got diverted here too  much from my subject, the reason behind is obviously to let the reader know that why WAPDA would not put this all live information on their website because that will put the orders in transparency and that is what the international pressure and local government do not want (that’s against the interests of those nations).

However, the grip of WAPDA’s IT department is so weak that when I searched wapda on Google and that is my habit which saved me here that I always search rather than typing in the address bar, the Google told me that visiting this website can be harmful. This is a bit shocking as the website’s domain is and it is a government’s website, however I checked that on 7th April, the date of writing of this blog is 10th April and who knows from how long it has been hacked. Well hacked is probably not a right word here, what probably has happened that the OS it’s developer is using is pirated (shouldn’t be a shock, it’s WAPDA) or he has been installing pirated software on the system and there is probably no anti-virus on the web developer’s system as well as web server. So, this malware got it’s way all up to the one of the most important websites of Pakistan.

Here are few screen shots:

May Allah bless Pakistan!

Get Pakistan Breaking News app for Android now!

Tutorial: Using IE Developer Tools as Firebug in Mozilla Firefox

There was a time when development for Javascript and CSS was restricted mainly because IE was the only main browser around (basically because it was shipped with your copy of MS Windows) and even the other browsers like Opera and Netscape were not able to listen to the web developer needs. Then came around, Youtube, GMail, Facebook, all of them giving rise to the concept of RIA (Rich Internet Applications) and at the same time Firefox was launched (2004). Firefox was an open source project which in turn allowed thousands of developers around to write what they want as plugins and someone came up with the idea of Firebug, that bug caught the web development community like fire and this plugin has more than 117,085 weekly downloads at the time of this writing. If  you ask any web developer that which plugin is his/her favourite, firebug will always get mentioned at the top and due to all good reasons. I remember coding Javascript before the firebug, when to check and debug a javascript array, I would have to write alert(array.length) and that will pop-up an alert box with array length and then imagine my page is getting updated after 1 second or that array is in a function who is running in loop.. bang! … just to inspect an instruction in that loop, that alert box will appear after every 1 second and ultimately I would have to kill my browser to get rid of it. Not the case any more. Then came around Ajax, I remember JS frameworks such as YUI and jQuery weren’t around in those days and I wrote my first function to make an Ajax request using XMLHttpRequest and after that telling my colleagues that the problem in writing Ajax code is that, you don’t get to see what is happening behind the request. A real nightmare? well we are lucky now, that dark period for client-side web scripting is over.

I don’t think if you are a web developer and you are not aware of firebug but this can be the case that you are a web developer and you are still sticking with the Firefox just because you love firebug and web developer toolbar. Most non-techie people around the globe still love IE (some of them are still on IE6 because that came with their MS Windows XP installation) and they constitute more than 70% of  the total, so if you are going to develop for general public or for a client who just couldn’t understand that why I don’t use IE and why Firefox is my favorite browser, you need to have a look at your web application in IE before shipping it and I am telling you it could always go wrong as you may be calling a function whose one parameter Firefox is ignoring and still executing the code while IE wouldn’t ignore and will stall altogether. Luckily, IE8 comes bundled with IE developer tools (developer tools were around from some time but installing them on and off was a real nightmare, at-least for me). But yes I can hear what you are saying, most of the times, IE will throw an error and it will have very “helpful” error description such as “Unspecified Error” and it will point at totally wrong line in the source code and you will have to do your guess work to eliminate the problem, anyway, with developer tools you could see something in place of nothing.

Enough discussion, here is your 3-minutes crack-on graphical tutorial to use IE developer tools just like your native firebug console and web developer toolbar on Firefox.

First load your desired web page in IE8 which you want to inspect by pressing F12 or by selecting Tools > Developer Tools in IE8.

Second always remember that to inspect a script you need to select it first and start debugging.  In IE Developer Tools > Script tab > Select script > Start Debugging

Selecting Debugging Source

Inspecting Javascript Variables

The most convenient use of firebug for me is of seeing the JS variable values as I develop a complex client-side application. As I discussed above, you don’t want to see alert boxes again and again, IE developer tools, do that for you in two ways.

You can use console to see any output messages. To differentiate between these messages, different console.log APIs are available:

  • console.log
  • console.error
  • console.warn
  • console.assert

My favorite in firebug was console.debug but I left using that long ago because IE Developer Tools do not support console.debug and this will break your code. Secondly firebug allows you to format those error message, IE  Developer Tools do not support that (or at-least something I am not aware of). The output of these console messages will be exactly like something you see in firebug. For the record, you write code like this:

var myvar = 0;

IE Developer Tools Log Messages

The other way is slightly different, can be used for the same purpose but is related to only variables, you are able to see variable values at your breakpoints, so you have the time to analyze them.

To create a break point, hover your mouse on the line number you want to mark as break point and click, a red dot will appear on the left beside the line number, now when you will start debugging, browser will stop executing it just before the line you marked as break point.

Then go to the right hand pane of IE developer tools and select Watch > Click to add the variables you want to see and developer tools will let you know the variable name, value and type at the break point.

Watch variables at break point

You are able to change variable values at this moment as well, just when you are watching a variable in Watch tab, open Console tab and assign new value to the variable to see how it will behave after you hit Play again. In the same manner you are able run any instructions which are not in source code but you want to run them at break point to analyze the effect.

Part 1: Running script at break point

Part 2: IE Developer Tools console with new variable value

Now go back to the Watch tab and see the updated value.

Part 3: Watch updated variable value

Profiling Javascript

Another important need for a web developer who do not think that JS is just a scripting language and it just has bits like getting an element and changing it’s value at run time etc. but it is so important that the developer actually needs to optimize the run times and to see how many times a function is getting called, JS profiler is just what saved our lives in firebug, it is here too in IE Developer Tools.

You need to select Profiler tab in Developer Tools > Start Profiling, do something on your page like refresh or wait for sometime if that is something you want to check and then Stop Profiling, Developer Tools will give you a complete report of JS activity done in that time span, listing Functions, count of the calls made and inclusive, exclusive time etc. Same information can be seen in Call Tree view if you select call tree from Current View.

Javascript Profiler

View Generated Source

If you ever worked with Ajax, you would probably know the importance of seeing the DOM once your Ajax call has been made and your DOM has got updated. In Firefox I use Web Developer Toolbar to see Generated Source, in IE Developer Tools, you can view the same by going into View > Source > DOM, you can view the Original source code and the selected element’s DOM as well.

View Generated Source

Outlining Elements on the Page

Another important tool of firebug is when you can outline the elements on your page to see where they are residing, like the divs or tables etc. I specifically use Web Developer Toolbar instead to outline and see the cause of cosmetic issues. IE Developer Tools comes with this solution as well. You can go to Outline in menu and select the type of elements you want to outline or to select an individual element you can go to Any Element and add the name of the element to view outline.

Outlining Elements

There are plenty of other functions which Developer Tools support like you can also see the CSS of an individual element by going to Find > Select Element by Click and then clicking on the element, just like you do for inspect element tool in firebug. You can view Images information or disable scripts, CSS, change the browser modes to render the page in IE7, validate your HTML (this will take you straight to W3C website and if you are working on localhost on your system, chances are W3C will refuse to check your code), CSS etc and you can even re size your browser to see your pages in different resolutions.

There is no doubt, Microsoft was under pressure from the developer community to bundle the developer tools with IE because after the arrival of Firefox, the whole development scenario got changed and developers want to develop more rich applications for the web. I personally havn’t adopted IE for my core development but it is handy to check my code every now and then in IE to see if everything is fine there and if not, using Developer Tools makes the life easier by allowing you to debug the code.

Feel free to comment if you have anything to say!

About me

Just another Londoner writing about life in the city, politics in general, technology and other gossips. Keep following as this will not be like any other blog.

If you want to get in touch personally, feel free to ping me on linkedin:

YUI Dialog: Hiding the Dialog Panel in IE – Bug Resolved

This fourth installment in YUI series is basically about firing a bug which appears to be IE (Internet Explorer) only. This is when you have opened an iframe in dialog widget and showing another resource using frame.src and relying on native

close : true

parameter of YUI Dialog widget to show a close button to the user on top of the dialog and when user clicks it, your dialog panel get hidden. Works very well in Firefox and Chrome but when I went to test in my IE8 installation, it went wrong.

The Error

The error was this, when I was closing the dialog panel in IE, it was getting hidden but leaving some traces of it back, in most of the cases, border of a table which was in the iframe, meaning dialog was not getting properly hidden. It was also not allowing me to click or change any thing in the background elements  in the parent page, reason because IE was still thinking that dialog is on top of those elements.

The Code

The code I was using to pop up a new dialog panel to show a new regular page to the user in dialog iframe:

<script type="text/javascript">        
 // Instantiate the Dialog
 var addCons = new YAHOO.widget.Dialog("addCons",
 {   width : "965px",
 y: 15,
 x: 500,
 modal: false,
 visible : false,
 constraintoviewport : true,
 draggable : true,
 monitorresize : true,
 close : true});
 var DialogShow = function(e, args, o){
 var frame = document.createElement('iframe');
 frame.src = "";
 frame.width = "100%";
 frame.height = "580";
 //subscribing to the on show event
 addCons.showEvent.subscribe(DialogShow, addCons);
 YAHOO.util.Event.addListener("showHL", "click", function(o) {;});

I tried couple of work arounds but this idea really works well that ofcourse the dialog panel’s body is having problems, then just set the body to null on hide event.  So I subscribed the hide function with the hideEvent of dialog:

var DialogHide = function(e, args, o){
 o.setBody(' '); //set the body to null to avoid IE problem
 //subscribe the hide event
 addCons.hideEvent.subscribe(DialogHide, addCons);

Another requirement was to enable the user to press ‘Esc’ key to hide the dialog panel. We need a Key listener event then from yui utils to listen on key 27 (which is Esc key). Add the following bit of code just before we render the dialog widget:

var keylistener = new YAHOO.util.KeyListener(document, { keys:27 },          
 { fn:addCons.hide,
 }, "keyup" );
 addCons.cfg.queueProperty("keylisteners", keylistener);

View the example source code to have a look at the full source code.

View YUI Dialog Example in New Window

YUI Calendar: Using and modifying multiple calendar picker instances on single page

In this third installment of how to create and modify existing widgets from YUI Javascript library, I will explain how to create multiple instances of calendar widget of YUI2. There are many examples of how to use Calendar widget on YUI’s official website but for my application, the requirement was to to schedule multiple actions on the same page, giving each one a date of its own, so I developed my calendar widget with the example found here.  As a matter of fact if you really want to include multiple elements of a same type on a HTML page, you assign them different ids so that they can be accessed and called appropriately (just like you do with your babies).

You can see in the example I have built on, we are using here the power of Dialog container of YUI, we are using its button and context features to support our pop-up calendar.

It’s best that you first see my example code working and then I will explain the code.

View Multiple YUI Calendar Example in New Window

If you see the source code of example, you will see what I have really done is that, I have passed a unique ID for each calendar instance through declaring

<script type="text/javascript">

Then I enclosed all of the code in a function, which accepts the calendar ID and each variable which declares the calendar, gets embedded with this calendarID so that whenever a user uses any instance of the calendar, my widget knows about which calendar we are talking about and the calendar instance needs to update which fields. The same id is needed to be embedded in HTML fields which we are updating through (of-course using powerful features of DOM manipulation given by YUI)

Dom.get("month-field"+calendarID).value = month;
Dom.get("day-field"+calendarID).value = day;
Dom.get("year-field"+calendarID).value = year;

and at the end we really need to ensure that our HTML bits have those IDs

<span id="datefields1">
 <label for="year-field">Year:</label>
 <input id="year-field1" type="text" name="year" value="" style="width: 3em;">
 <label for="month-field">Month:</label>
 <input id="month-field1" type="text" name="month" value=""style="width: 2em;">
 <label for="day-field">Day:</label>
 <input id="day-field1" type="text" name="day" value=""style="width: 2em;">

Note the input id parameter, which is year-field1, month-field1 and day-field1, you can create as many calendars as you want, if you have specified the input ids and declared calendars with those ids.

There is one other bit which I have manipulated is the default behaviour of calendar when it updates a field, I was required to have date stamps in the format of YYYY:MM:DD while the calendar would update the fields in the format of YYYY-M-D format, for this functionality there may be some call given by YUI Calendar widget itself because I have seen several type of formats floating around in examples section but for me it was really quick to modify my function to include preceding zeros (if there are none) to month and day before I populate the the DOM elements:

//This modification is done to cater calendar out from yui to
//give always the leading zeros for months and days, in case they
//dont have
 var month = ''+aDate[1]+''; //convert month into a string
 var day = ''+aDate[2]+'';    //converty day into a string
 var year = ''+aDate[0]+'';    //converty year into a string 

//embed the preceding 0 if month is of 1 digit
 if (1 === month.length) {month = '0' + month;} 

//emebed the preceding 0 if day is of 1 digit
if (1 === day.length) {day = '0' + day;}

Other than these you will see how this function is subscribing certain events. One important event is to hide the pop-up calendar when a user presses ‘Esc’ key

// Pressing the Esc key will hide the Calendar Menu and send focus back to
 // its parent Button
 Event.on(window["oCalendarMenu"+calendarID].element, "keydown", function (p_oEvent) {
 if (Event.getCharCode(p_oEvent) === 27) {
 }, null, this);

For the calendar I am using default button provided by YUI CSS, you can change it by declaring your own calendarpicker button style in CSS like:

#calendarpicker button {
 background: url(../../images/calendar_icon.gif) center center no-repeat;
 text-align: left;
 text-indent: -10em;
 overflow: hidden;
 *margin-left: 10em; /* For IE */
 *padding: 0 2em;    /* For IE */
 white-space: nowrap;

change the background URL to your own image.

Feel free to comment if you have any better ideas to make this example more robust.

YUI Panel: Changing buttons and re-using a panel on same page

YUI is a natural Javascript library, it is different from jQuery and other Javascript frameworks due to its closeness to original JS where it supports you to build widgets and enhance the user experience, the other JS libraries such as jQuery and Dojo are incredibly easy to work in but they divert you so much from the original language that they become almost a language of their own. The closeness of YUI to the Javascript at the one end gives you the depth to work at your own ease and develop whatever you want, on the other hand it proves to be a bit difficult for the beginners, probably that is the reason, you will not find much support for YUI around, YUI has its own forums where the original developers of YUI reply in time-efficient manner as well but they speak at very high level and people to support at beginner and middle level are very less on Google.

So, I have decided to write some blog posts about the problems I faced and I was not able to find help on Google but then I figured out in some way (occasionally from the help of developers at where I got some hints and I made something out of it). I have already wrote first in this series which was about IE rendering problem in YUI tabs, today I will explain how you change modal panel buttons on the fly.

The requirement was to make a modal panel in YUI, which work at its own as a activation widget using Ajax (YUI connection manager). The idea was pop up a YUI panel when a user clicks on “Activate”, that modal panel will allow the user to enter details of when he/she wants to schedule the activation (where user can choose now or a later date) and then user can hit Submit and Cancel buttons. Uptil now its usual YUI panel which you will find in any YUI panel example, here is the example of making this panel:

//function to execute if user clicks on Cancel button
var handleCancel = function() {

// Instantiate the Dialog
 var dialog23 = new YAHOO.widget.Dialog("dialog23",
 { width : "340px",
 fixedcenter : true,
 visible : false,
 modal: true,
 constraintoviewport : true,
 hideaftersubmit: false,
 buttons : [ { text:"Submit", handler:handleSubmit, isDefault:true },
 { text:"Cancel", handler:handleCancel } ]
//delcare the call back
dialog23.callback = { success: handleSuccess,
 failure: handleFailure };
 // Render the Dialog

//attach the listener to Activate (button, div,
//span where ever you want to attach the click listener)
YAHOO.util.Event.addListener("Activate", "click",, dialog23, true);

A function of handleSuccess is missing in this example, I will leave that to you because in my code its very inter-related. The handleSuccess is where I make an Ajax request through YUI connection manager, once the request get submitted, I show a spinning wheel and then the Ajax response get shown to the user. The problem here is, you can easily show the response but changing the buttons at the bottom became a night-mare. Once the response is shown, you don’t really want to show the user Submit, Cancel buttons, what you really need there is a OK button so that user can acknowledge and on acknowledgment the panel hides away.

Here is how you change the button at the bottom of YUI panel:

//embed the OK button, on click handleOK function will be called
 dialog23.cfg.setProperty("buttons", [ { text:"OK",
handler:handleOK, isDefault:true }]);

and then write a funciton to act when user press Ok

//these are events which happen after a user clicks OK
 var handleOK = function() {
 //hiding the dialog box

There is one other approach I am using in this panel, that is if once activated, the user clicks on the Activate/Deactivate button again, what will happen then? You really need to make it dynamic.

For example your panel HTML was this:

<div id="dialog23">
<div align="left"><div id="ajaxResponse">
<form method="POST" action="timeschedule.php">
 <input type="hidden" name="buttontime" value="1">
 <div id="resp"></div>
<div>Enter the date here: <input type=text value=date name=date>

In this case before initializing anything get the all the ajaxResponse innerHTML in a variable like:

var div = document.getElementById('ajaxResponse');
//we are storing schedule HTML which we will restore at the end
var divHTML = div.innerHTML;

Now our ajax response will change the bits you get in ajaxResponse div, the input text box and other will be changed something like:

User specified action has been activated.

What you need now is to restore the original panel just when the user clicks OK, the handleOK function will get changed to this:

//these are events which happen after a user clicks OK
 var handleOK = function() {
 //restore the schedule HTML in case user wants to use it again
 div.innerHTML = divHTML; //populating the initial schedule HTML back
 //hiding the dialog box
 //rebuilding the submit and cancel buttons for re-use
 dialog23.cfg.setProperty("buttons", [ { text:"Submit",
handler:handleSubmit, isDefault:true },
 { text:"Cancel", handler:handleCancel } ] );

And here you will replace the buttons in the bottom of the panel again to Submit and Cancel.

I have elaborated enough here to give you an idea of how things work, its possible you are not working on same thing but my idea was really to give you ability to change buttons in the panel on the fly and to give you an idea that how you can use a panel again and again. If you need any further help, don’t hesitate to comment and I will try to reply as much as I can.

YUI Tabview and IE: Rendering Problem Solved

YUI Tabview is the easiest way I came around to organise your web pages into tabs, rather than using multiple selective navigation. YUI Tabview can easily be used to organise a very long page into chunks or you can give it an external source which it collects through Ajax and show to the user. Different parameters are available while making these calls such as cacheData and active, which allows you to cache the contents after fetching through ajax while active parameter let you decide that should tab fetch the data on page load or should it wait until user clicks on the tab explicitly.

There is a problem of inline script exeuction in YUI2 version (I haven’t tested YUI3 yet). Bubbling library gives an alternative to it. Bubbling Library is a YUI extension and by simply including dispatcher plugin of bubbling, you will be able to run inline javascripts in the tabs content. From inline I mean, the YUI Tabview by itself is a javascript, when it calls a source which also have <script type=”text/javascript”> tag in it, it breaks away and just do not show you anything. Dispatcher on the other hand makes separate nodes of each script tag and hence let you execute any javascript in your tabs.

Example to call tabs content through ajax using dispatcher plugin for YUI:

<div id="container">
<script type="text/javascript">
  	var tabView = new YAHOO.widget.TabView('contenttabview');
        YAHOO.plugin.Dispatcher.delegate( new YAHOO.widget.Tab({
        label: 'Leave a comment',
        dataSrc: 'yourexamplefolder/yourexamplepage.php',
        cacheData: true,
        active: true 

When I started using YUI Tabview, the first hurdle was to execute inline javascript which I was using for form validation etc, dispatcher solved, but just when I was about to finish the module development and went on IE (I was developing on Firefox) to check, it just didn’t went well, for those pages which had tabs with lots of content in it, IE just seemed to break its while fetching data through Ajax. It wouldn’t get the whole script running and would die out somewhere in middle. Luckily I had a universal footer and I got it straight away that footer is not executing that means browser is just not getting there.

The Solution:

After getting the problem, solution was simple, just call your tabs script only when the whole of your browser’s DOM is ready and loaded. There is a very handy functions of YUI2 Event Utility:

//which works like

 function init() {
    YAHOO.util.Dom.setStyle("hidden_element", "visibility", "");

But I will stick with native javascript function of


Here is how you modify the above example to work with IE to solve any potential rendering problems:

<div id="container">
<script type="text/javascript">
function tabs(){  	
       var tabView = new YAHOO.widget.TabView('contenttabview');
        YAHOO.plugin.Dispatcher.delegate( new YAHOO.widget.Tab({
        label: 'Leave a comment',
        dataSrc: 'yourexamplefolder/yourexamplepage.php',
        cacheData: true,
        active: true 
window.onload = tabs;

Happy Coding 🙂

Time Efficiency – Controlling Java applet from Javascript especially if you make round-trips to the web page from applet

My application architecture is like this,  for the easiness I will say that there is a clock on my page which a java applet updates every second, that clock shows the server time (in actual my java applet is updating other data as well). This java applet runs continuously once the page get loaded, I am loading it at the end of the page and it is a faceless applet.

Then I have this form for example:

<form id="liveClock">
  <input type="hidden" id="DivID" value="Nothing Yet">
  <input type="hidden" id="DivVal" value="Nothing Yet">

Now my java applet on the page, places the DivID which needs to be updated in DivID element and value of it in DivVal element.

Say after java applet places the DivID and DivVal, these elements look like this:

<form id="liveClock">
  <input type="hidden" id="DivID" value="Clock">
  <input type="hidden" id="DivVal" value="11:02:59">

A javascript function then picks up the data from the DivID and DivVal and updates the Clock div on the HTML page.

<script type="text/javascript">
function updateClock(){
//get the input element data placed by java applet
var DivID = document.getElementById("DivID");
var DivVal = document.getElementById("DivVal");
//now get the clock div
var clock = document.getElementById(DivID);
//check if we really have got the clock div element
if(clock != null){

After placing the data in input elements, java applet calls the updateClock function of javascript, which executes and update the clock on the page. Why applet is not directly updating the div element because applet is also used to update several other elements on the page and each update is coming at once in the form of a comma separated string, explaining all that is beyond the scope of what we are trying to achieve here.

Ok, applet is now running every second, placing data, then calling javascript and javascript is then updating the fields on the html page.  Java on its website says that if you are updating javascript on the web page from Java applet, avoid making round trips, the primary reason is that java applets are multi-threaded while javascript in a browser is single threaded and my applet is indeed a multi-threaded applet, however, I am using one thread explicitly to update the contents on the page while the other one to fetch the update from the back-end.

The problem I was facing that from time to time, whenever my applet is sitting there, sleeping for sometime and then updating the content, if user navigates away from the page, it produces some errors like DivID was not found or updateClock was not defined, while both are there in HTML page.

Root Cause of the Problem

Root cause of the problem was my browser was slow to unload and tear down the java applet while moving to another page but my applet was faster in execution and supposedly its 500ms wait finished while the browser has unloaded the DOM containing DivID element but applet would still try to go and update the element, that will throw errors in the browser.

The Solution:

The solution is simple:

in your HTML page header:

function closeIt()
  document.liveClock.APPLETID.PageLoad = 0;
window.onbeforeunload = closeIt;

where APPLETID is the ID of your applet element on the page. Then in your java applet declare a public integer PageLoadand initialize it with one

public int PageLoad = 1;

Now just when you write to the javascript through doc.eval(string), check the PageLoad variable

if(PageLoad == 1){

So, we are turning off our applet’s writing abilities just when browser is about to unload the page. The onbeforeunload event of javascript is not very famous but becomes very handy in this case.

Hence, we have worked around a problem to which both browser and java wasn’t addressing.

Happy Coding 🙂

Get Adobe Flash player