Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

Javascript - how to create static variables

 totalStaticFun = function(sum) {
        if(typeof self.cnt != 'number')cnt = sum;
        return cnt;
    };

the value that is returned remains static in javascript
Click here to View more...

Javascript prototypes?


Prototypes can extend any class you want by adding a property or a method. By calling,
[source:javascript]
String.prototype.alertMe = function() {
alert(this);
}
[/source]
you are adding the method alertMe() to every String object of your application.
It uses less memory because javascript creates only one instance of the function and uses references to it.
Click here to View more...

Extend javascript classes


The intrinsec objects of javascript (String, Number, Date, etc) are missing a lot of handy methods. God knows why. Example, you don’t have a trim() function on a String object. Maybe the developers thought that it was easy enough to write theString.replace(/^\s*|\s*$/g, “”) to trim a string but that’s not the kind of ugly code I want to see everywhere in my projects. It’s unesthetical. To do this, I have to use prototype.
So I want to add a trim() method to all my objects that are String class.

String.prototype.trim = function()
{
return this.replace(/^\s*|\s*$/g, “”);
}

Click here to View more...

Create objects in object-oriented javascript

There are hundreds of way of writing OO javascript, I tried a lot of the most commons and I finally adopted one : oo using prototypes.

1. Creating an empty class

I like cats so here’s a complete example for a cat that meows.
First, I create an empty class.
[source:javascript]
function Cat() {
}
[/source]
Hmmmm… that looks a lot like a function. In fact, it’s a function. Why classes are function? Because javascript is a functional language. More on that later (maybe).

2. Creating the constructor

When I have a cat that meows, I want to see its name. I add a name property that is initialized in the constructor of the class.
[source:javascript]
function Cat(name) {
this.name = name;
}
[/source]
What is this? This, is a reference on the current instance of the object. By calling this.name = name, we instantiate an public variable for the object that has the value name (the name of the cat).


3. Adding a instance method

As I said earlier, I want the cat to meow. So, I will add a meow() method to the class that will be available to every instance.
[source:javascript]
function Cat(name) {
this.name = name;
}
Cat.prototype.meow = function() {
alert(“meow!”);
}
[/source]
I used the class’ prototype. This is one of the hundred ways of adding a method but it’s the best way because we create a single reference for all the objects of that class.

4. Using variables of an object

Hey, didn’t you read the specs? I said that I wanted to see the name of the meowing cat.
[source:javascript]
Cat.prototype.meow = function() {
alert(this.name + ” : meow!”);
}
[/source]
Did you see? I used the this (reference on the current instance of the object). By doing that, I simply call the variable that I defined in my constructor (see point #2).

5. Making the cat meow

Now I’m ready to make the cat meow. On the onload property of the body element, I call a function named bodyOnload.



In the bodyOnLoad function, I create a Cat object and call the meow() method.
[source:javascript]
function bodyOnLoad() {
var mistigri = new Cat(‘Mistigri’);
mistigri.meow();
}
[/source]
I should see an message box with the message “Mistigri : meow!” inside.
Click here to View more...

What are PROTOTYPES in javascript?

Javascript is using prototypes and is the only language I know that is doing it. What is the idea behind it? Simple. With prototypes, you can extend (add methods/properties) any class you want anywhere you want anytime you want even if you are not the owner of that object. Object-oriented purist will be shocked but I am more than pleased with that.

Why using prototypes?

It’s memory-friendly
By adding a method to a class prototype, you are creating a single occurence of the function that is referenced by every objects of that type.

It’s easy



To add a method to a class, no need to create a new class. Juste write TheClass.prototype.theMethod = function() {//code here} and it’s done.
It’s fun!
Maybe not as fun as drinking kool-aid but compared to the complexivity of other languages, we have a champ.

How to use prototypes

Simple. Write the [NameOfTheClass].prototype.[NameOfTheExtension].
You want to add a trim function to the String object?
[source:javascript]
String.prototype.trim = function()
{
return this.replace(/^\s*|\s*$/g, “”);
}
[/source]
You want to add an oldValue property to the string
String.prototype.oldValue = “the old value”;
Beware! All the new String objects and the one already declared will have a property with the value “the old value” inside.
Click here to View more...

INHERIT classes in javascript

There are hundreds of ways to do inheritance in javascript but a single one is simpler, cleanier and prettier than all the other ones.

A one-liner

To inherit a class in javascript, it’s a one-liner
  1. TheSubClass.prototype = new TheParentClass();
As simple as that!


Where to write the one-liner

The problem with that one-liner is where should it goes? Once again, the answer is simple : after the constructor of the sub-class. It may look strange but it is extremely effective.
  1. /* The constructor of the Mammal class */
  2. function Mammal() {
  3. }
  4. /* The constructor of the Cat class */
  5. function Cat() {
  6. }
  7. // The magic that inherits Cat from Mammal is here!!!!!
  8. Cat.prototype = new Mammal();

Is this true inheritance?

In the hundreds of other ways of inheriting classes in javascript, I think that this is the only one that is a true inheritance. What do I mean by true inheritance? I mean that javascript recognizes it as a sub-class of the class. Check this out!
  1. /* Above code goes here */
  2. // Create a cat
  3. var theCat = new Cat();
  4. // Check if the cat is an instance of the Cat class
  5. if (theCat instanceof Cat) {
  6.     alert("theCat is an instance of the Cat class");
  7. }
  8. // Check if the cat is an instance of the Mammal class
  9. if (theCat instanceof Mammal) {
  10.     alert("theCat is an instance of the Mammal class");
  11. }
If you execute this code, you’ll see that the cat is an instance of the Cat class and the Mammal class.
Click here to View more...

Create objects in object-oriented javascript


In short, you can use private variables when you return another scope when declaring a class.
  1. function Cats() {
  2.   var nameList = []; // private var
  3.        
  4.   // This is where you define another scope!
  5.   return {
  6.     add:function(name) {
  7.       nameList.push(name);
  8.     }
  9.   }     
  10. }


How does it work?

The magic lies in creating a different scope at the end of the class definition that does not include private variables. Then, private members are available in this scope and not outside of it, thanks to the power of closures.

Differences between private and public

These two classes definition shows the difference between the a class where all members are public versus a class where some members are private.
This is a class where all members are public.
  1. function PublicCats() {
  2.   // This is the list of cat names
  3.   this.nameList = [];
  4.  
  5.   // This is a method that I would like to be private but can’t
  6.   // It returns the last cat of the list
  7.   this.lastCat = function() {
  8.     return this.nameList[this.nameList.length-1];
  9.   }
  10.  
  11.   // Return the list of names
  12.   this.names = function() {
  13.     return this.nameList;
  14.   }
  15.  
  16.   // Add a name to the list
  17.   this.add = function(name) {
  18.     this.nameList.push(name);
  19.    
  20.     // Return the last cat just added
  21.     return this.lastCat();
  22.   }  
  23. }
This is the corresponding class where some members are private.
  1. function PrivateCats() {
  2.   // This is the list of cat names
  3.   var nameList = [];
  4.  
  5.   // This is a private method
  6.   var lastCat = function() {
  7.     // Note : I don’t use "this" to access private variables
  8.     // thanks to the power of closures!
  9.     return nameList[nameList.length-1];
  10.   }
  11.  
  12.   // These are our public methods!
  13.   // This is where we create another scope to
  14.   // avoid external objects to use the private variables.
  15.   return {
  16.     add:function(name) {
  17.       // Note : once again, I don’t use "this"
  18.       // to access the private variables and methods
  19.       nameList.push(name);
  20.       return lastCat();
  21.     },
  22.     names:function() {
  23.       return nameList;
  24.     }
  25.   }  
  26. }
In the above code, line 15 makes all the difference between the two classes.
Click here to View more...

Constants in javascript


Global constants

Ouch! That one hurts!  global variables are prohibited since 1992 by GVIP (Global Variables International Police). But sometimes, a man gotta do what a man gotta do. If you really can’t find any better solution, use this one.
[source:javascript]
var DISPLAY_TYPE_SMALL = 0;
var DISPLAY_TYPE_BIG = 1;

[/source]

Class constant

If you already know how to create objects you have to use the class functions technique (also knows as static or shared functions) to create a class “constant”.
[source:javascript]
// Create the class
function TheClass() {
}

// Create the class constant
TheClass.THE_CONSTANT = 42;

// Create a function for TheClass to alert the constant
TheClass.prototype.alertConstant = function() {
// You can’t access it using this.THE_CONSTANT;
alert(TheClass.THE_CONSTANT);
}

// Alert the class constant from outside
alert(TheClass.THE_CONSTANT);

// Alert the class constant from inside
var theObject = new TheClass();
theObject.alertConstant();

[/source]

As you saw, you can’t access the constant using the this variable (a reference to the current object) because the constant is defined on the class only and not the object.

Class enum

Sometimes, constants are not enough. You need to regroup them to be more logical. Example? I have three different display type : small, medium, big. I could do this
[source:javascript]
// Create the class
function TheClass() {
// Initialize the display type to big
this.displayType = TheClass.DISPLAY_TYPE_BIG;
}

// Create constants
TheClass.DISPLAY_TYPE_SMALL = 0;
TheClass.DISPLAY_TYPE_MEDIUM = 1;
TheClass.DISPLAY_TYPE_BIG = 2;

// Assign the small display type to the object
var theObject = new TheClass();
theObject.displayType = TheClass.DISPLAY_TYPE_SMALL;
[/source]

It works but they are not logically grouped. I would prefer to use an enumeration (enum)
[source:javascript]
// Create the class
function TheClass() {
// Initialize the display type to big
this.displayType = TheClass.DISPLAY_TYPE.big;
}

TheClass.DISPLAY_TYPE = {
small : 0,
medium : 1,
big : 2
}

// Assign the small display type to the object
var theObject = new TheClass();
theObject.displayType = TheClass.DISPLAY_TYPE.small;
[/source]

Click here to View more...

Javascript - format a number with commas and decimals

function formatNumber(value, decimalPlaces) {
        if(isNaN(value) || ""==value) {
            value = 0;
        }
        value = parseFloat(value).toFixed(decimalPlaces);
        return parseInt(value).toLocaleString().split(".")[0] + "." + value.split(".")[1];      
    }

Eg:  7389948 --> 7,389,948.00

If we want the reverse to happen ( 7,389,948.00 --> 7389948)
var a = receivedField.value.replace(/,/g, ""); 


Click here to View more...

Number rounding in JavaScript

JavaScript helps lay the foundation for rounding off numbers with the following method:
Math.round(x)
Using it, any supplied argument is rounded off to the nearest integer, and using the ".5" up rule. For example:
Math.round(25.9) //returns 26
Math.round(25.2) //returns 25
Math.round(-2.58) //returns -3
I

Want to display $25 in standard currency format? How about PI to finity and not beyond? Formatting numbers to specific decimal points entails still Math.round(), but padded with a little multiplication and division. See if you can identify the magic formula involved, with the below examples:
var original=28.453
 
1) //round "original" to two decimals
var result=Math.round(original*100)/100  //returns 28.45
2) // round "original" to 1 decimal
var result=Math.round(original*10)/10  //returns 28.5
3) //round 8.111111 to 3 decimals
var result=Math.round(8.111111*1000)/1000  //returns 8.111
 
In case you haven't picked up on it, the formula to round any number to x decimal points is:
1) Multiple the original number by 10^x (10 to the power of x)
2) Apply Math.round() to the result
3) Divide result by 10^x


Click here to View more...

Printing a large HTML table

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Test</title>
<style type="text/css">
    table { page-break-inside:auto }
    tr    { page-break-inside:avoid; page-break-after:auto }
    thead { display:table-header-group }
    tfoot { display:table-footer-group }
</style>
</head>
<body>
    <table>
        <thead>
            <tr><th>heading</th></tr>
        </thead>
        <tfoot>
            <tr><td>notes</td></tr>
        </tfoot>
        <tr>
            <td>x</td>
        </tr>
        <tr>
            <td>x</td>
        </tr>
        <!-- 500 more rows -->
        <tr>
            <td>x</td>
        </tr>
    </tbody>
    </table>
</body>
</html>


Note
<style>
@media print
{
table {page-break-after:always}
}
</style>

Click here to View more...

Print contents of an HTML element with JavaScript

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252" />
<title>JavaScript printing</title>
<script type="text/javascript">
  var win=null;
  function printIt(printThis)
  {
    win = window.open();
    self.focus();
    win.document.open();
    win.document.write('<'+'html'+'><'+'head'+'><'+'style'+'>');
    win.document.write('body, td { font-family: Verdana; font-size: 10pt;}');
    win.document.write('<'+'/'+'style'+'><'+'/'+'head'+'><'+'body'+'>');
    win.document.write(printThis);
    win.document.write('<'+'/'+'body'+'><'+'/'+'html'+'>');
    win.document.close();
    win.print();
    win.close();
  }
</script>
</head>
<body>
<a href="#" onclick="printIt(document.getElementById('printme').innerHTML); return false">
Print
</a>
<br />
<div id="printme">Only this part of the page is printed</div>
</body>
</html> Click here to View more...

Print stylesheet for printing html content

A print stylesheet formats a web page so when printed, it automatically prints in a user-friendly format. Print stylesheets have been around for a number of years and have been written about a lot. Yet so few websites implement them, meaning we're left with web pages that frustratingly don't properly print on to paper.
It's remarkable that so few websites use print stylesheets as:

  • Print stylesheets enormously improve usability, especially for pages with a lot of content (such as this one!)
  • They're phenomenally quick and easy to set up
Some websites do offer a link to a print-friendly version of the page, but this of course needs to be set up and maintained. It also requires that users notice this link on the screen, and then use it ahead of the regular way they print pages (e.g. by selecting the print button at the top of the screen). Print-friendly versions are however useful when printing a number of web pages at the same time such as an article that spans on to several web pages.

How to set up your print stylesheet

A print stylesheet works in much the same way as a regular stylesheet, except it only gets called up when the page is printed. To make it work, the following needs to be inserted into the top of every web page:
<link rel="stylesheet" href="print.css" type="text/css" media="print" />


Remove unwanted items

Usually it's just your organisation logo and page content that you'll want to appear on the printed version of the web page. You'll normally want to remove the header, left column and right column. You may also want to remove the footer (or some of it) from the printed version, unless it contains your contact details.
There may be certain isolated items you'd prefer weren't printed so you can simply assign these class="noprint" in the HTML. To get rid of these items, along with the header and navigation (assuming these are assigned  div id="header" and div id="nav") use the display: none command:
#header, #nav, .noprint {display: none;}
You may also want to remove certain images and adverts, especially animated images as these won't make sense when printed.

Format the page

There's nothing worse than printing off a web page to find the last few words of each line cut off. It's also annoying (and a waste of paper) when the left and right columns are left in, leaving a very narrow space for the content so the web page prints on to 15 pieces of paper.
Generally speaking, the three CSS commands you'll need are:
width: 100%; margin: 0; float: none;
These commands should be applied to any containing elements (div for a CSS layout and table for table layouts) to ensure the content spans the full width of the paper. So, the full CSS command would perhaps be something like:
#container, #container2, #content {width: 100%; margin: 0; float: none;}

Change the font?

Some print stylesheets do change the font size (often to 12pt) but this isn't generally a very good idea. If users increase text size on the screen then the text will print in this larger font size... unless you specify a fixed font size in the print stylesheet.
Other print stylesheets change the font family to a serif font (such as Times New Roman) as this is slightly easier to read from print. Whether you choose to do this or not is up to you as users may be a bit surprised to see a different font printed out.
Do also bear in mind that background images and colours don't print out by default. As such, you may wish to change the colour of text in a light colour so it has a reasonable colour contrast without its background.

Links

Print-outs are often in black and white so do make sure that links have a decent colour contrast. If not, assign links a slightly darker colour in the print out. For example:
a:link, a:visited {color: #781351}

 

Making the print stylesheet

When making the print stylesheet place the print CSS commands into the bottom of your main CSS file. As you keep adding more commands check how your web pages look on the computer screen (don't do this on a live website!). Keep adding commands until you're happy with the appearance, then cut these commands out of the main CSS file and paste into the print stylesheet.
To summarise, your print stylesheet may look similar to this:
/* Remove unwanted elements */
#header, #nav, .noprint
{
display: none;
}

/* Ensure the content spans the full width */
#container, #container2, #content
{
width: 100%; margin: 0; float: none;
}

/* Change text colour to black (useful for light text on a dark background) */
.lighttext
{
color: #000
}

/* Improve colour contrast of links */
a:link, a:visited
{
color: #781351
}

You've now got a print stylesheet! For something this quick and easy to set up that improves usability as much as it does, you'd be mad not to use one! Click here to View more...

Print content of page javascript

 The following code creates a hyperlink and uses the Javascript print function to print the current page:
<a href="JavaScript:window.print();">Print this page</a>

  1. function PrintContent()
  2. {
  3. var DocumentContainer = document.getElementById('historyListPanel');
  4. var WindowObject = window.open('',  
    "TrackHistoryData",
  5. "width=740,height=325,top=200,
    left=250,toolbars=no,scrollbars=yes,status=no,resizable=no");
  6. WindowObject.document.writeln(DocumentContainer.innerHTML);
  7. WindowObject.document.close();
  8. WindowObject.focus();
  9. WindowObject.print();
  10. WindowObject.close();
  11. }
  1. pass your table id or div id or contentid
Click here to View more...

onClick() confirmation script - easy way

onclick="if (!confirm('Are you sure you want to continue?')) {return false;}" Click here to View more...