Showing posts with label Web Development. Show all posts
Showing posts with label Web Development. Show all posts

Wednesday, June 30, 2010

Web designers, stop using splash ads!!!

Have you visited websites and got really annoyed by ads that span almost the whole page and flash suddenly out of nowhere, blocking you from doing anything meaningful on the page? If so, then welcome to the club – the club of disgruntled web users who get frustrated day in day out by such ads (sometimes called splash ads). But surprisingly, many web designers seem completely oblivious to their agony and keep using these ads on the home pages of their websites. Even hugely popular websites like Espnstar (see screenshot below), Cricinfo and Times of India, to name a few, are resorting to the use of these kind of ads.

Espnstar splash ad

I find ads in general to be obtrusive and irritating but as long as they are in the corner of the page and do not hinder your interactions with the “useful” elements on the page, they are bearable. But splash ads go a step further and make it impossible to use the site as long as they are in view. And as can be expected, the “close” button to get rid of this ad is so miniscule and well camouflaged that you will have to strain your eyes to spot it. I have been visiting Espnstar quite frequently these days thanks to the sports bonanza, what with Football world cup, Wimbledon, Natwest series and Formula 1 all happening simultaneously. But my experience on the site has been pretty frustrating thanks to these ads. I hope the web designers out there are listening to this feedback and stop using such ads soon.

Tuesday, December 30, 2008

Getting available screen space for web pages

One of the most common requirements when creating a web page is to get the
space available in the browser window where the content will be displayed. It is always preferable to fit the content into the available space to prevent scroll bars and reduce the effort required on the part of the user. A number of factors cause variations in
the width and the height available for the content of the web page, some of them
being,

  1. Windows Taskbar
  2. Status bar
  3. Toolbars (for eg., MSN toolbar, Google toolbar etc)

Because the user can have any combination of these things enabled, it is difficult to get the exact space and height available. Add to this the fact that different browsers support different sets of properties of the BOM and even for the common set of properties, they give different meanings. Hence, we need to combine multiple approaches to get the available space so that it works in almost all browsers. The code that will do exactly this is given below :

//Returns an array containing the available width and height
function GetWindowSize()
{
....try
....{
........var myWidth = 0, myHeight = 0;
........if (typeof (window.innerWidth) == 'number')
........{
............//Non-IE
............myWidth = window.innerWidth;
............myHeight = window.innerHeight;
........}
........else if(document.documentElement && (document.documentElement.clientWidth
document.documentElement.clientHeight))
........{
............//IE 6+ in 'standards compliant mode'
............myWidth = document.documentElement.clientWidth;
............myHeight = document.documentElement.clientHeight;
........}
........else if (document.body && (document.body.clientWidth
document.body.clientHeight))
........{
............//IE 4 compatible
............myWidth = document.body.clientWidth;
............myHeight = document.body.clientHeight;
........}
........return new Array(myWidth,myHeight);
....}
....catch (ex)
....{
........return null;
....}
}

The above code should suffice for almost all browsers and different browser versions. It is not advisable to use "Screen.availWidth" and "Screen.availHeight" since it doesn't return the correct values in case the user is using toolbars. I have tested the above code for IE and FireFox with and without toolbars and it worked like a charm.

Monday, December 29, 2008

Preventing JavaScript injection attacks

Whenever one is developing web pages that accept input from the user, one needs to be extra careful in order to prevent the extremely dangerous XSS (Cross Site Scripting) attacks. Typically, these attacks are carried out by users who input malicious scripts in the input fields provided on the web page. The scripts get executed when the page tries to display back the values that were input by the user. For example, if the user is presented with a field for entering his name, he may enter something like

ABC;<script>alert("This site is hacked")</script>

Now, whenever the site displays this user's name, the script also gets executed and the viewer of the page will get an alert box proclaiming "This site is hacked". Although this is a contrived example, there is the potential to do much more harmful things using the same technique. Skilled users can write scripts that can read data from cookies, for example, and send to another site (hence the name cross site scripting).

In order to prevent such things from happening, all one has to do is "Server.HTMLEncode" all the values that the user provides, assuming you are using ASP.NET. There are 2 places where you can do the encoding :

  1. You can do the encoding while storing the data in the database so that anytime those values are to be displayed to the user, they won't cause any problems.
  2. You can also do the encoding just before showing the values to the user. This technique can be used when you are just displaying the values without ever storing them in the database or in case you need to display the values before storing them in the database

What Server.HTMLEncode does is it converts all the special characters such as "<" and ">" to their ASCII equivalents so that the browser runtime engine interprets them as normal characters instead of interpreting and executing them. You can find the complete list of actions taken by this method here.

Remember to encode any and all values you accept from users to avoid having serious XSS attacks launched on your website.

Sunday, December 28, 2008

Weird behaviour of "onchange" event of Listbox in FireFox

The HTML listbox has an "onchange" event which is fired whenever the item selected in the listbox has been changed. The contents of the listbox can be changed either by clicking the corresponding item from the listbox or by using the up and down arrow keys or pressing the beginning alphabet of any of the items when the listbox has focus. Ideally, even when changing the selected item by using the keyboard, the onchange event should be fired. In fact, the event is fired in all major browsers except Firefox. With Firefox, the onchange event is called only when the listbox loses focus.

Suppose you have a form whose contents you would like to change based on the value selected in the listbox. For example, have different fields on the form based on whether the user is interested in Sports, Music, Dance etc. You can do this by capturing the item selected by the user in the onchange event and making the necessary changes by manipulating the DOM. However, you would have a problem with users using FireFox. To be able to capture the value every time the user makes a new selection, we need to add some javascript for the "onkeyup" event. The code needed is,

<select id="items" onchange='itemSelected();' onkeyup="this.blur();this.focus();">
</select>

All that needs to be done is to momentarily remove focus from the listbox so that the onchange event is called and then, set the focus again. Setting the focus again on the listbox is needed because, if we don't do that, the user will have the set the focus explicitly on the listbox every time he changes it's value with the keyboard - he wouldn't appreciate this if he wants to select a value which is 4-5 values further in the list from where he's currently at.

I spent nearly 2 hours trying to figure out why the onchange event wasn't getting called in FireFox. Hope this post will go some way in helping you reduce the debugging time in case you happen to come across a similar situation.

Sunday, December 7, 2008

Ignoring certain characters from user input in HTML Textbox

One common requirement when creating user input forms in websites is to not show some of the characters in a text box. For example, we would not want to show alphabets in input fields for dates and age. Similarly, we would not want to show numbers in an input field for name.

As it turns out, this is really easy to do with some simple JavaScript. We can accomplish this with the following steps :
  1. Identify the characters that need to be ignored (Black listing approach)
  2. Add an event handler for the key down event on the text box
  3. In the event handler, check whether the input character is one of the characters that needs to be ignored. For these characters, just return false from the event handler. This will prevent that particular character from reflecting in the text box
  4. Optionally, one can show an error message if one of the unwanted characters is input. This is done to avoid the user from getting confused when his inputs don't cause any changes in the contents of the text box

Here is the code for declaring text field in HTML :

<input id="'startDate'" type="'text'">

We can add the event handler in the HTML tag itself or in a Javascript function which will be called on the "onload" event of the body as follows :

document.getElementById('startDate').onkeydown = CheckNumber;

Here, we are using the "Key Down" event of the text box to check for the character input by the user. Finally, the event handler function code is as follows :

function CheckNumber(e)
{
....try
....{
........if (!e)
........{
............e = window.event;
........}
........var keynum;
........try
........{
............//IE : Get the code of the key the user pressed
............keynum = e.keyCode;
........}
........catch (err)
........{
............//Netscape/Firefox/Opera : Get the code of the key the user pressed
............keynum = e.which;
........}

/*Prevent any character not in the range 0-9 and not '/', backspace, delete or left and right arrow keys, Tab and Shift+Tab. ASCII Code : / is 191, Backspace is 8,Delete is 46, Left : 37, Right :39, Tab : 9, Shift + Tab: 16*/

........if (keynum != 191 && (keynum <> 57) && keynum != 8 && keynum != 46 && keynum != 37 && keynum != 39 && keynum != 9 && keynum != 16)
........{
............//Show error to the user to inform him that the input was invalid
............document.getElementById("dateErrorMessage").style.display = "inline";
............//Return false to prevent the character from being added to textbox
............return false;
........}
........else
........{
............//Remove error message if it's visible
............document.getElementById("dateErrorMessage").style.display = "none";
........}
....}
....catch (ex)
....{
........alert("Check number : " + ex.message);
....}
}

As can be seen from the comments, we first retrieve the ASCII code for the character typed by the user (as expected, we have 2 different ways of getting the value based on the browser type) . Then we check against the characters we will allow (I am using white listing here, one can use blacklisting also, as mentioned earlier. The right approach will depend on the number of conditions that need to be specified but generally white listing is preferred for 2 reasons. It will cause fewer problems in case you miss out on some conditions and this mistake will be easier to catch during testing. If the character doesn't fall within our white list, we show an error message on a label and then return false to prevent it from appearing in the text box. Otherwise, we do nothing so that the character appears normally in the text box.

So there you have it, a texbox that accepts restricted inputs. Customise for the type of inputs you want to allow/disallow.

Sunday, September 21, 2008

Javascript : Creating Textbox watermarks

One of the common requirements when working with web page forms is to have some default text show within a text box and make it disappear when the user enters something in the text box, in other words, create a text box watermark.

Now if you are working with ASP.NET then an easy way to do this is to use the AJAX Control Toolkit's 'TextboxWatermark' control and just link the AJAX control to the text box in which we want the watermark to appear. The AJAX control provides a number of options to control the watermark. However, if you are working with pure HTML pages then, you are stuck with Javascript and need to figure out a way to control the watermarking. I recently wrote some code to do the same and would like to share it in this post.

Assuming you have a html page added to your project, the following steps would enable the watermarking of the text box :

  1. The first step obviously is to define the basic HTML tag which will add a normal text box to your page. Here's a sample code for this :

    <input id="txtUsername" name="txtUsername">

  2. The next step is to define a variable which will store the string that will act as the watermark (Thanks Pratik for sharing this best practice with me). The advantage of creating a variable is that it makes it easy to perform comparisons (which will be mentioned in a later step) and also requires you to change the watermark text in only one place.

    var gcUsernameTbDefaultText='Please enter a username';

  3. The trick to have the watermark appear and disappear is to capture the 'onblur' and 'onfocus' events and manipulate the contents of the text box. The following code snippet shows functions being called for these 2 events.

    <input type="text" id="txtUsername" name="txtUsername" onfocus="clearTextbox('txtUsername',gcUsernameTbDefaultText);" onblur="showDefaultText('txtUsername',gcUsernameTbDefaultText);" />

    As you can see, the functions called when the events occur are passed the id of the text box on which the watermark is needed and also the watermark text, making these functions generic and usable with any text box.

  4. The last and final step is to implement the 2 functions that do the actual manipulation. So here they are :

    • function clearTextbox(objId,text)
      {
      try
      {
      var obj = document.getElementById(objId);
      //Clear the textbox only if the textbox contains the original default value
      if (obj != null && obj.value.toString().toLowerCase() == text.toLowerCase())
      {
      obj.value = "";
      }
      }
      catch (e)
      {
      alert(e.message);
      }
      }

    • function showDefaultText(objId,text)
      {
      try
      {
      var obj = document.getElementById(objId);
      if (obj != null && obj.value == "")
      {
      obj.value = text;
      }
      }
      catch (e)
      {
      alert(e.message);
      }
      }

So there you have it, simple text box watermarking. There are 2 improvements one can do on this implementation :

  1. Dynamically apply styles in order to show the watermark text in gray, with some sort of transparency and have the normal text with normal appearance
  2. This approach won't work with 'password' text boxes since even the watermark will appear as asterisks. This post talks about implementing watermarks for password text boxes