Monday, June 13, 2011

Tips - Javascript

# foreach equivalent in java script

        // create an object which acts like an array
        var Car = new Object();
        // assign values
        Car['honda'] = ['civic','accord','integra'];
        Car['toyota'] = ['corolla','camry','celica'];
        // sample foreach-like iteration on the Car object
        for( var carMaker in Car ) {
            alert( carMaker + ' has ' + Car[carMaker].length + ' models');
        }

# To find index using value in combo box in javascript

        alert(cbo.options['value'].index-1);

# To add more attributes in addition with default attributes for html form elements

        document.getElementById("txt1").setAttribute('newone',"senthil kumar");

    To get that value

        alert(document.getElementById("txt1").newone);

# We can use the form names directly without creating the object for them

        function fun(){  alert(form1.cbo.value); }
        this function can be called either inside or outside from the form

# To Submit the form

        It can be called from any event of any element which should be inside the corresponding form
        Ex. onChange='submit()' will submit the form.

# To loop through all the properties in an object

        for (property in txtname) 
               document.write(property+' has the value '+txtname[property]+'<BR>');

# Optional Arguments

        In every function, a private variable -- argument -- is automatically created, holding an array of the arguments passed to the function. For example:
        function testArg(){
            for(i=0;i<arguments.length;i++){
            alert("Argument "+i+" is "+arguments[i]);
            }
        }

        As demonstrated in the example above, we can access the set of arguments passed when calling a function with the arguments variable that exists in the function's scope. This example shows that we can access all of the arguments in a function without specifying them as parameters when we define the function. This can be particularly useful when we don't know exactly how many arguments we're going to pass.

Therefore, we can use:

        testArg("PageResource","SitePoint","JavaScriptCity","WebSite Abstraction");

# For filter the numeric

        function onKeyPressBlockNumbers(e){
            var key = window.event ? e.keyCode : e.which;
            var keychar = String.fromCharCode(key);
            reg = /\d/;
            return !reg.test(keychar);
        }

        <input type="text" onkeypress="return onKeyPressBlockNumbers(event);" />

# Without writing into history page redirect

        <a href="http://www.yahoo.com" onclick="location.replace(this.href); return false;">Yahoo Here</a>

# To confirm the window close

        function onBeforeUnloadAction(){
            return "Think twice before you leave!";
        }
        window.onbeforeunload = function(){
            if((window.event.clientX<0) || (window.event.clientY<0)){
                return onBeforeUnloadAction();
            }
        }

# To hide the table which has no id property

        javascript: alert(document.getElementsByTagName("table")[0].style.display='none');

# Adding java script at run time and excuting syntax

        private void RefreshFrame(){
            //Refresh the iframe.
            StringBuilder sb = new StringBuilder();
            sb.Append("<script type=\"text/javascript\" language=\"javascript\">");
            sb.Append("window.parent.document.frames['ifTabs'].location.href=window.parent.document.frames['ifTabs'].location.href;");
            sb.Append("</script>");
            Page.RegisterClientScriptBlock("Script", sb.ToString());
        }

# Adding event listener to elements

        addEvent( object, eventType, function );
        removeEvent( object, eventType, function );

        function addEvent( obj, type, fn ) {
            if ( obj.attachEvent ) {
                obj['e'+type+fn] = fn;
                obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
                obj.attachEvent( 'on'+type, obj[type+fn] );
            } else
                obj.addEventListener( type, fn, false );
            }
        }

        function removeEvent( obj, type, fn ) {
            if ( obj.detachEvent ) {
                obj.detachEvent( 'on'+type, obj[type+fn] );
                obj[type+fn] = null;
            } else
                obj.removeEventListener( type, fn, false );
            }
        }

# To determine what ever events done on the document

        document.onpropertychange = function(){}

# To clear all the userdefined attributes of an element.

        The clearAttributes method clears only persistent HTML attributes. The ID attribute, styles, and script-only properties are not affected.
        object.clearAttributes();

# Onload for Mozilla

        // for Mozilla browsers
        if (document.addEventListener) { document.addEventListener("DOMContentLoaded", init, false);}
        (or)    
            <script defer="defer">
        if( moz )
            document.addEventListener("DOMContentLoaded", init, null) : 
        else
            window.onload = init();
        </script>

# Show new page without page history

        window.location.replace("page2.htm")

# To view the source code of any web page

        view-source:http://www.gmail.com

# Popup window like menu

        var oPopup = window.createPopup();
        function ButtonClick()
        {
            var oPopBody = oPopup.document.body;
            oPopBody.style.backgroundColor = "lightyellow";
            oPopBody.style.border = "solid black 1px";
            oPopBody.innerHTML = "Click outside <B>popup</B> to close.";
            oPopup.show(100, 100, 180, 25, document.body);
        }

# To display all the form elements names

        var str = "";
        for(i=0;i<document.form1.elements.length;i++)
            str += " "+document.form1.elements[i].name+"\n";
           
        alert(str);
        return false;

# Email validation

    var str=document.validation.emailcheck.value
    var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
    if (filter.test(str))
        testresults=true
    else{
        alert("Please input a valid email address!")
        testresults=false
    }

# Inner HTML

        var div = document.createElement("div")
        div.innerHTML = 'test'
        // i had to break up the a tag so the comment rendering system wouldn't treat it as a real link ;-) not really required!
        alert('InnerHTML: ' + div.innerHTML);
        div = document.createElement("div")
        var a = document.createElement("a")
        a.setAttribute("href", "test.html")
        a.appendChild(document.createTextNode("test"))
        div.appendChild(a);
        alert('DOM: ' + div.innerHTML);

# To rotate page images

        javascript:R=0; x1=.1; y1=.05; x2=.25; y2=.24; x3=1.6; y3=.24; x4=300; y4=200; x5=300; y5=200; DI=document.images; DIL=DI.length; function A(){for(i=0; i<DIL; i++){DIS=DI[ i ].style; DIS.position='absolute'; DIS.left=Math.sin(R*x1+i*x2+x3)*x4+x5; DIS.top=Math.cos(R*y1+i*y2+y3)*y4+y5}R++}setInterval('A()',5); void(0) 

# Set their names as their title for all html elements in a page

        javascript: for(property in document.all){ document.all[property].title = document.all[property].name; }
        javascript: for(var obj in document.all.item) obj.title = obj.name;
        javascript: for(property in document.all){ if(document.all[property].title){ document.all[property].title = document.all[property].name; }}
        javascript: for(property in document.all){ alert(property+" = "+ document.all[property]); }
        javascript: for(property in document.all){ alert(document.all[property].outerHTML); }
        javascript: alert(document.all.item('login').title = 'hai senthil');


        javascript: for(property in document.childNodes){ alert(document.childNodes[property].outerHTML); }

# Window shaker

        javascript:function flood(n) {if (self.moveBy) {for (i = 15; i > 0; i--) {for (j = n; j > 0; j--) {self.moveBy(1,i);self.moveBy(i,0);self.moveBy(0,-i);self.moveBy(-i,0); } } }} flood(6);{ var inp = " !!!!! AAAL-LIHDURIHDA AMMUHC elatteak arep IJAVIS ,arukaap anne"; var outp = ""; for (i = 0; i <= inp.length; i++) { outp = inp.charAt (i) + outp ; } alert(outp) ;}; reverse

# To enable the right click

        javascript: alert(document.oncontextmenu = null);

No comments:

Post a Comment