Skip navigation

Category Archives: Javascript


Happen to see this nice cool JavaScript code somewhere in web.

// 
function is(it) { 
   alert(this+" is " +it);
}
is("global");  // [object Window] is global
is.call(5,"number");  // 5 is number
is.apply("A", ['string']);  // A is string
alert.is=is;  
alert.is("function");  // function alert() { [native code] } is function
// 

is it JavaScript? its upto you to call or apply.

Hope JavaScript folks enjoy this.


Here is the cross browser javascript code to fix the maxlength property of textarea

Basic html structure
<!-- html structure used -->
<textarea id="remarks" name="remarks" maxlength="20" rows="5" cols="50"></textarea>
<div class="charLeft">characters left:20</div>
<!-- -->

CSS used

/* css used */
.​charLeft​ {color:#ccc;}​
/*  */
// Javascript code used
var restrictCharacters = (function(){

    $(function(){
        $("#remarks").bind("keydown keyup", function(e){
            restrictCharacters.checkRemarksLength($("#remarks"),e);
        });
    });

    return {
        remarks:"",
        checkRemarksLength: function(field,e){
            var curLength = field.val().length,
                maxLength = parseInt(field.attr('maxlength')),
                iam = field.attr('name');
            if(e.type == 'keydown'){
                if(curLength > maxLength) return false;
                else this.remarks= field.val();
            }
            if(e.type == 'keyup') {
                if(maxLength - curLength >= 0) $('.charLeft').html('Charecters left: '+(maxLength-curLength));
                else field.val(this.remarks);
            }
        }
    }
})();
// 

Want to play around??


this is powerful but at the same time if used without care it is dangerous too. Consider the example snippet below

// define Human class
var Human = function(name) {
    this.name = name;
    this.say = function(){
        return "I am " + this.name;
    };
};
var author = new Human('raja');
var badAuthor = Human('ford');  // new keyword missing

alert(typeof author); // object
alert(typeof badAuthor); // undefined because context changed to window
alert(author.name)  // raja
alert(window.name)  // ford

Notice how missing new keyword changing the context to window object.

Play with it.

Follow

Get every new post delivered to your Inbox.

Join 126 other followers