Friday 29 July 2011

jQuery Plug-ins : how to build?

Plugin Authoring Guidelines
http://docs.jquery.com/Plugins/Authoring

Building Your First jQuery Plugin
http://blog.jeremymartin.name/2008/02/building-your-first-jquery-plugin-that.html

A Plugin Development Pattern
http://www.learningjquery.com/2007/10/a-plugin-development-pattern

Wednesday 27 July 2011

Hiding JavaScript code from older browsers

It is straighforward, follow the steps below:

1. Immediately after the opening <script> tag, put a one-line HTML-style comment without the closing characters, so that the first two lines of your script would look like this:

<script language="JavaScript">
<!--


2. At the end of your script, put the following two lines:

//-->
</script>


Thus, your HTML file will contain the following fragment:

<script language="JavaScript">
<!--
Here you put your JS code.
Old browsers will treat it
as an HTML comment.
//-->
</script>

Old browsers will treat your JS code as one long HTML comment. On the other hand, new JavaScript-aware browsers will normally interpret JS code between the tags <script> and </script> (the first and last lines of your JavaScript code will be treated by the JavaScript interpreter as one-line comments).

Tuesday 26 July 2011

Auto-boxing JavaScript primitive types

Primitive Types in JavaScript

Number values, like 1,
string values, like "",
the boolean values true and false,
and the special values null and undefined

Object types in JavaScript

Date objects,
regular expression objects,
function objects,
arrays
and literal objects like {}

Auto-boxing
Whenever you access or assign to a property of a number, string or boolean, a temporary object value (of the Number, String or Boolean class, respectively) is created with the same naked value as the primitive value, but that temporary object is only available to that property access, and does not replace the primitive value that your variable references.

Example

Calling split() on primitive value.


var str = 'primitive-valued string literal';
console.log( str.split(' ') ); //=> obviously ["primitive-valued", "string", "literal"]
str.split = function(){ return 'overridden!'; };
console.log( str.split(' ') ); //=> still ["primitive-valued", "string", "literal"]


Calling split() on String object.


var str = new String( 'primitive-valued string literal' );
console.log( str.split(' ') ); //=> obviously ["primitive-valued", "string", "literal"]
str.split = function(){ return 'overridden!'; };
console.log( str.split(' ') ); //=> "overridden!" that's more like it


Read more >>

Debugging JavaScript using Firebug console

Sometimes the fastest way to find bugs is just to dump as much information to the console as you can. Firebug gives you a set of powerful logging functions that you can call from your own web pages.

console.log

The easiest way to write to the Firebug console looks like this: console.log("hello world")

You can pass as many arguments as you want and they will be joined together in a row, like console.log(2,4,6,8,"foo",bar).

Logging object hyperlinks

console.log and its related functions can do a lot more than just write text to the console. You can pass any kind of object to console.log and it will be displayed as a hyperlink. Elements, functions, arrays, plain ol' objects, you name it. Clicking these links will inspect the object in whatever tab is most appropriate.

String formatting

console.log can format strings in the great tradition of printf. For example, you can write console.log("%s is %d years old.", "Bob", 42).

Color coding

In addition to console.log, there are several other functions you can call to print messages with a colorful visual and semantic distinction. These include console.debug, console.info, console.warn, and console.error.

console.log() and older browsers



You can write a script which creates console functions if they don't exist. For example following script can be used to alert the given value when console.log() is unavailable.


<script type="text/javascript">

if (!window.console) console = {};
console.log = console.log || function(s){alert(s)};

console.log('testing')

</script>



Click here to read more

JavaScript For...In Statement

The for...in statement loops through the properties of an object.

Syntax


for (variable in object)
{
//code to be executed
}


Note: The code in the body of the for...in loop is executed once for each property.

Example

Looping through the properties of an object:


<script type="text/javascript">

var person={fname:"prince",lname:"thomas",age:30};

for (var property in person)
{
document.write(property + ": " + person[property] + "<br>");
}
</script>


The output will be

fname: prince
lname: thomas
age: 30

Friday 22 July 2011

What is "this" in jQuery?

When is this a DOM element?

The short answer is - usually. Scripting with jQuery quite often involves the use of callback functions. Whether handling an event, iterating a collection of nodes, animating an image, or applying a dynamic filter, callbacks are used to invoke your custom code at the appropriate time. To make things easy for you, jQuery sets the scope of the callback function to the element which is the subject of the callback. For example, when we want to handle a mouse click event for an element we bind a handler function to the event like so:


$('#myButton').bind('click', function() {

// our code to handle the click event goes

// here, in the callback function

});


When a user clicks the 'myButton' element, jQuery invokes the callback function that was passed to the bind method. But when it invokes our callback it sets the current scope to the DOM element that initiated the event, in this case the 'myButton' element. jQuery does this as a convenience. The object you are most likely to need in the event callback is the element that triggered the event. And what easier way to have access to it than by using the this keyword? So within the callback function it can be assumed that this is the relevant DOM element.

Converting this to $this

When this is a DOM element it is often in the context of code that needs to access or manipulate it in some way. This, of course, is something that jQuery excels at. So how do we use the power of the jQuery API when this is a DOM element? Just turn this into $this:


$('div').each(function() {

// 'this' is a DOM element

// wrap 'this' in a jQuery object

var $this = $(this);

// now we have the full jQuery API at our disposal

var title = $this.attr("title");

if (title != null)

$this.prepend("<h2>" + title + "</h2>");

});


Click here to read more

Setting multiple CSS attributes at a time using jQuery

This can be done by passing a comma seperated list of "attributeName:value" pairs to the .css() jQuery method.

Syntax

.css({ attributeName-1:"value",attributeName-2:"value",...attributeName-N:"value" })

For example to the following line sets the font-family and font-size of all paragraphs in the page.

$("p").css({fontFamily:"verdana", fontSize:"25px", color:"green"});

This can also be aschieved by the following script.


$("p").css("fontFamily","verdana");
$("p").css("font-size",25);
$("p").css("color","green");

jQuery .css("height") and .height()

The difference between .css('height') and .height() is that the latter returns a unit-less pixel value (for example, 250) while the former returns a value with units intact (for example, 250px). The .height() method is recommended when an element's height needs to be used in a mathematical calculation.

jQuery height() vs outerHeight()

.height()
Get the current computed height for the first element in the set of matched elements. This does not include the padding, border and margin.

.outerHeight([includeMargin])
Get the current computed height for the first element in the set of matched elements, including padding, border, and optionally margin.

"includeMargin" is a optional boolean indicating whether to include the element's margin in the calculation.

$(window).height(); // returns height of browser viewport
$(document).height(); // returns height of HTML document

$("#IdofYourDIV").height(); // returns height of "IdofYourDIV" excluding padding, border and margin

$("#IdofYourDIV").outerHeight(); // returns height of "IdofYourDIV" including padding and border but excluding margin

$("#IdofYourDIV").outerHeight(true); // returns height of "IdofYourDIV" including padding, border and margin

Getting selected text from DropDownList using jQuery

Try

$("#IDofYOurDropDownList option:selected").text();

$("#IDofYOurDropDownList").text() will return you all the "text" values of the dropdown list.

BUT

$("#IDofYOurDropDownList").val(); will give you the selected value.

Wednesday 20 July 2011

Iterating an Array using jQuery each() method

Try the below JavaScript code.



var arr = ['a','b','c'];

$.each(arr, function(index, obj) {
// 'this' is the object of the current iteration
alert(this);
//This will alert a or b or c in each iteration
});

$(arr).each(function(index, obj) {
// 'obj' is the object of the current iteration
alert(obj);
//This will alert a or b or c in each iteration
});

jQuery eq(index) method

Reduce the set of matched elements to the one at the specified index.

index is an integer indicating the 0-based position of the element.When index is a -ve value, counting is done backwards from the last element in the set.

Consider a page with a simple list on it:

<ul>
<li>list item 1
<li>list item 2
<li>list item 3
<li>list item 4
<li>list item 5
</ul>

We can apply this method to the set of list items:

$('li').eq(2).css('background-color', 'red');

he result of this call is a red background for item 3. Note that the supplied index is zero-based, and refers to the position of the element within the jQuery object, not within the DOM tree.

Providing a negative number indicates a position starting from the end of the set, rather than the beginning. For example:

$('li').eq(-2).css('background-color', 'red');

This time list item 4 is turned red, since it is two from the end of the set.

Triggering an event handler only for the first occurance of an event using jQuery one()

This method is identical to .bind(), except that the handler is unbound after its first invocation. For example:

$("#bob").one("click", function() {
alert("This will be displayed only once.");
});



After the code is executed, a click on the element with ID "bob" will display the alert. Subsequent clicks will do nothing. This code is equivalent to:

$("#bob").bind("click", function( event ) {
alert("This will be displayed only once.");
$(this).unbind( event );
});



In other words, explicitly calling .unbind() from within a regularly-bound handler has exactly the same effect.

jQuery selectors

jQuery offers a powerful set of tools for matching a set of elements in a document.

If you wish to use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[\]^`{|}~ ) as a literal part of a name, you must escape the character with two backslashes: \\. For example, if you have an element with id="foo.bar", you can use the selector $("#foo\\.bar").

All Selector jQuery('*')
Selects all elements.

Attribute Equals Selector [name="value"]
Selects elements that have the specified attribute with a value exactly equal to a certain value.
$('input[type="radio"]') //selects all radio buttons in the document

Attribute Starts With Selector [name^="value"]
Selects elements that have the specified attribute with a value beginning exactly with a given string.
$('div[id^="inputfield"]') //selects all DIVs whose id starts with "inputfield"

Child Selector (“parent > child”)
Selects all direct child elements specified by "child" of elements specified by "parent".
$("div.inputfield > input.ageBox") //select all input fields with class "ageBox" within DIVs with class "inputfield"

Descendant Selector (“ancestor descendant”)
Selects all elements that are descendants of a given ancestor.
$("form input") //selects all input field in the form

Class Selector (“.class”)
Selects all elements with the given class.

Element Selector (“element”)
Selects all elements with the given tag name

ID Selector (“#id”)
Selects a single element with the given id attribute.

Has Attribute Selector [name]
Selects elements that have the specified attribute, with any value.
$('div[id]') //Selects all DIVs with Ids

:first-child Selector
Selects all elements that are the first child of their parent. While :first matches only a single element, the :first-child selector can match more than one: one for each parent. This is equivalent to :nth-child(1).

$("div span:first-child").css("text-decoration", "underline")

last-child selector
Selects all elements that are the last child of their parent.While :last matches only a single element, :last-child can match more than one: one for each parent.

Multiple Attribute Selector [name="value"][name2="value2"]
$('input[id][name$="address"]') //Finds all inputs that have an id attribute and whose name attribute ends with "address"

Multiple Selector (“selector1, selector2, selectorN”)
Selects the combined results of all the specified selectors.

Click here to read more about jQuery selectors from jQuery API

Trying jQuery in W3Schools TryIt Editor

Click here to open W3Schools TryIt Editor

Copy and paste the below html into the editor. Cick "Edit and Click Me>>" button on top to see the result. Now you can add your own HTML and JavaScript and test it.

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script language="javascript">

//alert(jQuery);

$(document).ready(function () {

alert($('div').length);

});
</script>

</head>

<body>

<div>Test1</div>
<div>Test2</div>

</body>
</html>

Monday 18 July 2011

DateAdd JavaScript function

The following JavaScript function can be used to add the given "duration" to the given "datepart" i.e. "day", "month" or "year". See the example calls and return values and the actual function definition below.


document.write(DateAdd('1/1/2011', 10, 'day')); //returns 11/01/2011
document.write(DateAdd('1/1/2011', 10, 'month')); //returns 31/10/2011
document.write(DateAdd('1/1/2011', 10, 'year')); //returns 31/12/2020
document.write(DateAdd('1/3/2011', 1, 'year')); //returns 29/02/2012

function DateAdd(startDate, duration, datepart)
{
var day = startDate.split("/")[0];
var month = startDate.split("/")[1];
var year = startDate.split("/")[2];

if (typeof (datepart) != "undefined")
{
switch(datepart.toLowerCase())
{
case "year":
year = Number(year) + duration; day = Number(day) - 1;
break;
case "month":
month = Number(month) + duration; day = Number(day) - 1;
break;
case "day":
day = Number(day) + duration;
break;
}
}

var endDate = new Date(year, month - 1, day);
//Month starts from 0. 0 is Jan, 11 is Dec


/*new Date(2012, 0, 0) -- returns 31/Dec/2011
new Date(2012, 1, 0) -- returns 31/Jan/2012
new Date(2012, 1, -1) -- returns 30/Jan/2012
new Date(2012, 13, 1) -- returns 1/Feb/2013
*/


day = endDate.getDate();
month = endDate.getMonth() + 1;
year = endDate.getFullYear();

day = ((day + "").length == 1) ?
("0" + (day + "")) : (day + "");
month = ((month + "").length == 1) ?
("0" + (month + "")) : (month + "");

return ( day + "/" + month + "/" + year );
}



You might be also interested in DateDiff() function which can be used to find the difference in days between 2 given dates.

Friday 15 July 2011

Creating PDF Documents with ASP.NET and iTextSharp

The Portable Document Format (PDF) is a popular file format for documents. Due to their ubiquity and layout capabilities, it's not uncommon for a websites to use PDF technology. For example, an eCommerce store may offer a "printable receipt" option that, when selected, displays a PDF file within the browser.

This article on www.4guysfromrolla.com investigates iTextSharp, a .NET open source library for PDF generation, showing how to use iTextSharp to create PDF documents from scratch. It starts with an example of how to programmatically define and piece together paragraphs, tables, and images into a single PDF file. Following that, it explores how to use iTextSharp's built-in capabilities to convert HTML into PDF.

Click here to read the article



Filling in PDF Forms with ASP.NET and iTextSharp

What is iTextSharp


iText# (iTextSharp) is a port of the iText open source java library for PDF generation written entirely in C# for the .NET platform.

Click here to DOWNLOAD iTextSharp

Wednesday 13 July 2011

Setting "nowrap" using CSS white-space property

To achieve the same results as a TD nowrap (<td nowrap="true">) using cascading style sheets, use the following:

white-space: nowrap;

white-space
The white-space property specifies how white-space inside an element is handled.

Property values
normal, nowrap, pre, pre-line, pre-wrap, inherit

JavaScript syntax: object.style.whiteSpace="nowrap"

Please note that replacing white spaces by " " does the job, too. "nbsp" means "Non Breakable SPace".

Sample code

Example 1.
<table id="mytable">
<tr><td></td><td></td></tr>
</table>

CSS

table#mytable tr td{white-space:nowrap;}

Example 2.
<table>
<tr class="nowrap">
<td></td>
<td></td>
</tr>
</table>

CSS:

tr.nowrap { white-space:nowrap; }

td { white-space:inherit; }

OR

tr.nowrap td {white-space:nowrap;}

Debuggging Javascript using developer tools in IE8

We can now debug Javascript with the developer tool bar plugins integreted in IE8 and IE9.

Follow these steps

1. Open developer tools bar (From Tools menu OR by pressing F12)
2. Click on "Script" tab
3. Click on "Start Debugging"

Now you can set breakpoints, use watch to inspect variables during runtime, see call stack etc ...

Debugging JavaScript using Firebug

FireFox add-on Firebug comes with built-in JavaScript debugger. Click here for the details.

What is Firebug?

Firebug integrates with Firefox to put a wealth of web development tools at your fingertips while you browse. You can edit, debug, and monitor CSS, HTML, and JavaScript live in any web page.

Tuesday 12 July 2011

parseInt('08') returns 0 with Javascript

I came across a rather interesting problem with the Javascript parseInt() function a couple of days ago; if the value is a zero padded string and is '08' or '09' then parseInt() will return 0.

parseInt('08') returns 0

The leading zero in the string tells the Javascript engine that it is an octal number. Because 8 and 9 are not valid numbers in octal, parseInt returns 0. This is expected behaviour because they are not valid octal integers and parseInt returns 0 because the first valid number encountered is a zero.

The solution

After a quick bit of research when I had this problem, I discovered the parseInt function has an optional 'radix' parameter which specifies the base to use. By passing 10 as the base it solves the leading 0 issue, for example:

alert( parseInt('08', 10) );

will show the number 8 in an alert dialog, whereas:

alert( parseInt('08') );

would display 0.

Conclusion

To be on the safe side it's probably always a good idea to pass the radix parameter to the parseInt function to ensure the values returned are what you expect them to be, especially if they might contain leading zeroes.

Friday 8 July 2011

jQuery AJAX slow in Firefox, fast in IE

This is true when you run the application from Visual Studio. Try after creating an IIS application or deploying to your developement server.

jQuery Each() Method

The jQuery library provides a method, Each(), which will loop through each element of the target jQuery object.


$( "#selector" ).each(

// For each item in the "selector", run this code. The "index" is the
// loop iteration index on the current element.
function( index ){

// Bind the onclick event to simply alert the
// iteration index value.
$( this ).bind (
"click",
function(){
alert( intIndex + " of " + $( "#selector" ).length);
}
);
}
);

Thursday 7 July 2011

CSS Image Opacity / Transparency

The CSS3 syntax for transparency is opacity:x

where x can be a value from 0.0 - 1.0. A lower value makes the element more transparent.

Image Transparency - Mouseover Effect



<img src="yourimage.jpg" style="opacity:0.4;"
onmouseover="this.style.opacity=1;"
onmouseout="this.style.opacity=0.4;" />

Click here to see the W3Schools.com example

How to get MonthName from DateTime in C#?

Following syntax can be used to get month name from current date

4 letter format
DateTime.Now.ToString( "MMMM" )

3 letter format
DateTime.Now.ToString( "MMM" )

string CurrentMonth = String.Format("{0:MMMM}", DateTime.Now).ToString();


Click here for more custom DateTime format strings

C# method to turn first letter to upper case

Can be done in different ways.


private string TurnFirstLetterToUpper(string s)
{
string firstLetter = s.Substring(0,1);
return firstLetter.ToUpper() + s.Remove(0,1);
}



Response.Write(TurnFirstLetterToUpper("programming")); //Ouput: Programming


Another one


string s = "coding";
string firstLetter = s.Substring(0, 1);
s= s.Replace(firstLetter, firstLetter.ToUpper()); //You should be careful while doing this, bcs String.Replace() will replace all the occurances of "firstLetter" in "s"

Response.Write(s); //Ouput: Coding


String.Replace(string,string):
Returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string.

String.Remove(int,int):
Deletes a specified number of characters from the string beginning at a specified position.

Tuesday 5 July 2011

Calculate DateDiff using JavaScript

This script will let you know how long you have to wait for the New Year

<script type="text/javascript">

//Set the two dates
var today = new Date();

var endofyear =new Date(today.getFullYear(), 11, 31); //Month is 0-11 in JavaScript

if (today.getMonth()==11 && today.getDate()==31)
alert("Happy New Year " + today.getFullYear()+1);
else
{
//Set 1 day in milliseconds
var one_day=1000*60*60*24;

//Calculate difference btw the two dates, and convert to days
alert(Math.ceil((endofyear.getTime()-today.getTime())/(one_day))+
" days left until New Year!");
}
</script>

You might be also interested in DateAdd() function which can be used to add day/month/year to give date.

Generic IComparer to sort strings alphabetically

Sorting a list is one of the common tasks for a developer. It is handy to have a generic function to do this. See the example below. It sorts the employees by their name.


class Employee
{
public string Name { get; set; }
public string Email{ get; set; }
}

//Create Employee List
List<Employee> employees = new List<Employee>();
Employee emp = new Employee();
emp.Name = "Joe";
emp.Email= "joe@somewhere.com";
employees.add(emp);

emp = new Employee();
emp.Name = "Bell";
emp.Email= "bell@somewhere.com";
employees.add(emp);

//Sort Employee List albhabetically
employees.Sort(new GenericComparer());

//Generic IComparer to do the sorting
public class GenericComparer : IComparer<object>
{
public int Compare(object x, object y)
{
System.Collections.CaseInsensitiveComparer c = new System.Collections.CaseInsensitiveComparer();

if (x is Employee && y is Employee)
return c.Compare(((Employee)x).Name, ((Employee)y).Name);
else
throw new ArgumentException();
}
}

//You can replace the CaseInsensitiveComparer.Compare() call with the following line if you want to do a case-sensitive search
return string.Compare(((Employee)x).Name, ((Employee)y).Name);


Assume you have another List where Department is


class Department
{
public string Name { get; set; }
}


It will be handy if you can write something like the below line to sort the department list similar to the employee list.


departmentList.Sort(new GenericComparer());


Not a biggie. Just modify the Compare() function.


public int Compare(object x, object y)
{
System.Collections.CaseInsensitiveComparer c = new System.Collections.CaseInsensitiveComparer();

if (x is Employee && y is Employee)
return c.Compare(((Employee)x).Name, ((Employee)y).Name);
//Below condition is new
else if (x is Department&& y is Department)
return c.Compare(((Department)x).Name, ((Department)y).Name);
else
throw new ArgumentException();
}


Then you should be able to sort the department list successfully by calling
departmentList.Sort(new GenericComparer());