02 Dec

HTML5 Drag, Drop and FileReader in JavaScript

HTML5 Logo

I love JavaScript. And combine that with the awesome power of HTML5 and I have an ice cream with generous serving of hot chocolate sauce on top.

Till HTML5 came about, there was no way in which JavaScript could receive a Drag & Drop event from the File System. Sure you could drag and drop elements inside browser window but not files from outside the window.

Plus JavaScript had no way in which it could process a file selected in an input[type=file] control on the client side. So if you wanted to upload a set of images to an online gallery you could only preview the image or check its properties after the upload completed. And it would be such a pain to realize that you selected the wrong set of images to start with. So re-upload!

In the new HTML5 supported browsers, one can write methods to process a file using the new File API. Although not strictly part of HTML5, it is currently supported only in Firefox 4+ and Chrome 7+ and other browsers are quickly falling in line.

So JavaScript’s events “dragover”, “dragleave” and “drop” can now respond to files dragged and dropped from the file system. And the “FileReader” object can read text files, file properties like size, name, path etc., read an image file and load a preview – all on the client side using plain JavaScript.

Check out the sample demo here.

So here is how to get started:

The addEvent method is my handy library function to attach Event Listeners to DOM elements in a cross browser fashion. The event object passed to the event listener contains a property “dataTransfer” which contains the reference to the selected/dropped files.

TIP: Remember, during a drag and drop, it is the element that receives the drop that will contain the dropped files. It need not be an input[type=file] control.

To give a feedback to the user that the page is responding to the drag and drop, I have incorporated the following technique:

Now to process the uploaded files. JavaScript has got this new object called the FileReader which is what I am using here:

We create a FileReader object, bind an onload event handler to the reader which will process the read file and perform the necessary operations to update the UI (as required) and then we call the reader.ReadAsText() method to read the text data of a file. We can even use the reader.ReadAsDataUrl() method to read binary image data as an encoded Data URI.

And that’s it. We have the power to process files client side now!

01 Dec

US and Me

Okay so I got this offer to join a company in the US as a SharePoint Trainer for a long term basis. As this was a great opportunity, I took it. Being the typical “namma bengalooru huduga”, never been out of Bangalore (atleast not longer than a month), never stayed in a hostel, never cooked a proper meal for myself, it was a big decision to make.

So here is my experience first time in the US.

Pre-Visa Interivew (H1B)

  • My company sent me the Visa related documents including a letter from the company stating why they need me and other documents as submitted to the USCIS.
  • I visited https://www.vfs-usa.co.in/USIndia/Index.html and followed the instructions to fill and submit the DS-160 form.
  • The documents my company sent me contained one document called the I-797B Notice Of Action. I was asked to take my passport and this document to the HSBC Bank in Bangalore (Kasturba Road) to pay the Visa Interview Fee and collect the challans.
  • Using the I-797 and the visa fee receipt, I booked my visa interview date in the US Embassy in Chennai. At that time there were no visa interview slots so I had to wait a few days for interview slots to clear up. I don’t know if it is allowed for a person to take an appointment in a US Embassy other than the one mentioned in your consular district.
Visa Interview
  • I got an early morning slot for the interview. I wanted to drive down to Chennai in my car with my mom. So I left Bangalore the previous morning. Chennai was a pleasant drive. About 6 hours with stops.
  • We stayed in a relative’s place and went for the interview early in the morning.
  • The interview was a smooth process.
  • I am not the guy who’ll say hold a 100 people’s feet to get to the US but it is extremely demoralizing to fail in anything, especially a visa interview when I had driven all the way down there!
  • So here are MY tips for the interview:
    1.  Organise your documents. Buy a couple of good high quality folders. One for all the junk documents that your company will provide you. You may never be asked to show these documents but you are required to have them. In the other folder, keep the important documents like your Passport, Degree Certificates, Resume, Offer Letter, I-797, Letter from employer etc.
    2. It is a good idea to know exactly where each document is in your folders. The biggest bungle people do in front of the interviewer is to scramble through a single folder looking for that one important sheet.
    3. Dress formal. Dress to impress. But don’t over dress and make yourself look too eager to get to the US.
    4. Be natural, act natural. Answer questions as if you have got nothing to lose even if you fail.
    5. Be confident, be cheerful. Greet the interviewer and ask how he/she is doing first.
    6. Answer to the point. Don’t give long stories. But don’t give the impression that you have memorized your answers. Think about the question asked for a second, frame your sentence and reply. Even if you know the answer, act as if you have put some thought into the question.
Travel to the US (Packing & Pre-Flight)
  • My company sent me the tickets. They booked on Qatar Airways and I later learnt that they are a very good airline.
  • I sold my car. Had foreclosed the loan and had the hypothecation removed earlier. Maybe did not get the best price for it. But it was hassle free.
  • Went in for a International Driving Permit to be made. The Jayanagar RTO had just shifted to their new facility. The IDP cost me about Rs.600. Need the passport, tickets and existing DL copies along with about 4 passport size photographs.
  • As usual, I received a ton of advice about what to pack and what not to pack. I wanted to travel with minimal luggage but somehow I ended up having to remove stuff b’cos I was over the 46kg limit. Yes, trans-Atlantic flights are allowed 2pcs of baggage 23kg each as check-in baggage. Apart from that you are allowed a small kit bag with a 7kg limit plus one laptop bag.
  • I realised only at the airport that they don’t weigh the laptop bag or the cabin baggage strictly. All that matters is that you don’t pack any stuff like powders/lotions/un-processed food items/liquids/deodarants or things like swiss knives etc. in these bags.
  • I packed in about 3 sweaters (I was headed to Fairfax, VA where temperatures reach negative Fahrenheit), 2pairs of thermals, gloves, skull caps, inner wear, office wear, jeans & casuals and my trustworthy Sapient woolen pullover. Had a couple of friends help me with some shopping as well.
  • Bought new shoes, slippers and a large trolley kit. Packed a pressure cooker (forgot the weight!), couple of heavy duty vessels & pans, a coffee filter, plates, tumblers, spoons.
  • Also went in the regular MTR ready to eat foods, sambar, rasam, vangibath and puliyogare powders.
  • Went to my regular doctor for a prescription for common allergies and ailments. Went to the pharmacy and bought all of them for stocking. Made sure to collect a bill and carry it with me on flight.
  • Packed all my required electronics and associated cables. Backed up my laptop files in my portable drive and carried it. Left the laptop back at home for mom. I was gonna get a newer powerful one in office anyway.
  • And thanks to my friend Sharath’s advice, I did a web check-in so that I can avoid the long check-in queue. And indeed it helped. The check-in queue was windingly looooong and the quick bag drop off was just 3-4 passengers long. Qatar also had the feature to pre-select my seats. I was naive so I selected a window seat. People usually prefer the aisle seats on long flights.
  • I was not aware of having to make a food preference 36hrs before flight departure. By not doing so, I risked not having anything vegan to eat on the flight.
  • Make sure you carry all the required documents in your cabin baggage/laptop bag. Passport, I-797, Employment Offer Letters, USCIS documents, destination address etc. Its ok to carry a camera in your cabin baggage. Its worth it.
  • I had planned to carry my Vodafone SIM to US. So carried my phone too. Activated International Roaming 24 hours before departure.
Travel to the US (Flight & Immigration)
  • The day of the flight was a painful one. The people I really wanted to come drop me off to the airport couldn’t/didn’t make it. Even after they had 6 months to prepare and plan for it. Was really depressed over it and it took me a couple of weeks to get over it.

Departure at Bangalore

  • No job can be done well beforehand. The last 4-6 hours before leaving the house were the most hectic and productive packing hours. Got prints of required emails, maps, phone numbers etc. Cello-taped my own name and destination address stickers to the baggage. Do not lock any of your luggage. Had to even visit the lawyer to get a power of attorney made in my mom’s name.
  • Booked a Tata Sumo to drop and return everyone. Made sure it has a top carrier for luggage. Rs.1500 for that. Reached the airport 3 hours prior. After all good bye’s and a coffee, I went in. That was it. A new phase of life. No turning back now.
  • An airline representative handed me a form to fill for emigration, directed me to the quick bag drop line as I had checked in online. This was a good move.
  • Then I filled up the form. This is some emigration step which no one had told me about. The person basically asked me if I planned to settle down in the US permanently etc, asked for my passport & visa and verified it and let me through. I was cleared in my passport that I do not need an Emigration Check. Indian passports now carry an ECR seal if you are required to clear Emigration Checking for some major countries. Basically people who have a minimum 12th standard pass certificate or those above age 50 will not have this seal. I thought people without the seal don’t have to go through this emigration step but looked like everyone was going through it.
  • I boarded the flight to Doha. Qatar Airways are one of the best airlines in terms of seating comfort and hospitality I am told. I wouldn’t know for sure as this was my first international flight. But I for sure did not have any space cramps for my legs.
  • 5 hours later I landed in Doha. I took my first step on international soil (concrete actually). For some reason while the flight was descending I got a severe headache above my eyebrows and it was uncontrollable. It subsided only when the plane landed. I was not prepared for another round of such a headache when the plane lands next in DC. So I asked for the Airport clinic, consulted the doctor who gave me a couple of tablets to swallow and told me it would be fine. It was free.
  • I had a 4 hour gap between flights but the BLR-DOHA flight landed about 90 mins late and that left me about 25 mins to make my way through a stringent security check and board the next flight to DC. They got everyone to even remove shoes, didn’t let me carry my water bottle. It was a special water bottle and I didn’t want to let go of it. So then he told me that I can’t carry the water in it.
  • The flight to DC was a long 14 hour flight. The air-hostesses will force you to pull down your window blinds as the bright sun might disturb other passengers. The plane takes a long route from the Middle East over Europe, Britain, Greenland, Canada and finally the US.
  • Seeing Greenland from the air was a treat to the eye.

Greenland from the air

  • While the plane was about 2 hours from landing we were issued a form to fill called the I-94. This form would be used in immigration and would be stapled to your passport. You will need to have this form on the passport as long as you are in the US. And will need to have it removed when you leave.
  • It is important that you fill this form accurately with information as-is in your passport. I made a goof-up here as my visa has my first name as FNU, I filled up this form with my first name as FNU. I later had issues with they did not give me an SSN till even after 6 weeks. I am still waiting for it. More on that later.
  • The plane landed in the US. The DC airport was a let down. It was too simple and barren. Something unexpected for the capital of the country.
  • After landing you need to go through immigration wherein you will be asked questions about the purpose of your coming to the US etc. If you answer straight and with a smile, this should not take more than 2 minutes at the counter. But the queue to the counter took me about 2 hours with a heavy backpack and a big kit bag in my hand. No trolley’s at this point. My Tip: Once you get out of the plane, rush to the immigration counter. Atleast saves 150 people in your plane from getting ahead of you. If you want to use the restrooms, do it on the plane!
  • Next I collected my check-in bags. They had been taken off the belt and placed on the floor. I was told that trolleys are not free like in India but I didn’t have to pay for my trolley.
  • I took a taxi and headed to my hotel. Cost me $40 including a 15% tip to the driver. I for one thing didn’t understand the concept of this tip. In India we fight with auto drivers to give us Re.1 change.
  • First thing after checking in at the hotel was to make phone calls back home and to my brother and announce that I have arrived! The hotel had free wi-fi but I left my laptop at home. My N97 had a Skype app but it was off due to low battery. I took out my charger only to realise that it is an Indian charger (the round pin was the problem, not the voltage). So I had to find a converter first up. I went to a nearby pharmacy and got a universal converter. Yes, a Pharmacy. A pharmacy here basically sells everything, including beer and wine!
  • Crossing the road here requires you to reach a pedestrian crossing and push a button by the traffic light to request for a crossing.  I didn’t know that. So I waited 5 mins at the signal not knowing what to do. Then finally crossed without any pedestrian green just to see a car come to a screeching stop next to me from the wrong side!! OMG I checked the wrong side of the road for traffic and crossed! Whoa that was frightening. Next 2 days I was getting over that incident and crossing a road was the biggest challenge for me in the initial few days.
  • I suffered hardly any jet-lag. I did nothing special so don’t ask me. My friend Sharath’s tips were:
    1. Take a walk in the daylight if possible. No matter how tired you are.
    2. Do not sleep till atleast 10pm local time. Avoid all urges to take a nap before local bed time.
  • Next morning I was to report to office and begin my new career!
  • Next items that needed to be settled were:
    1. A Phone Connection.
    2. A Laptop (from office)
    3. A Bank Account
    4. Apply for an SSN
    5. Find an apartment/room to share.
    6. Get a Car!
    7. Get a Driving Licence
    8. Get my name rectified in my passport and have the FNU removed by the Indian Embassy.
And my story with those items is equally long so I will end this issue here and write about those in my next post!
People prepare a lot when travelling to the US. I had not done even 10% of that kind of preparation. I wanted to learn my way around. Not go in with my cup full. I wanted to be Jake Sully! And I have been doing OK so far. I could rent a car with Enterprise.com and go around thanks to my International Driving Permit. People complain that it is a big hand-written book. Who cares! As long as it is accepted, I am happy. Period. The Indian IDP is accepted in most US states and you can drive with it for upto 6 months after arriving in the US.

So I am in the US