Musings

A random collection

Archive for the ‘javascript’ Category

TECH: JavaScript 101

Write a basic HTML section

<script type="text/javascript">
document.write("<h2>Hello World!</h2>");
</script>

Define a function and a call to it:

<script type="text/javascript">
function message()
{
  document.write("Hello world!");
}

message();
</script>

Calling a javascript file

// somescript.js
function message()
{
  document.write("Hello world!");
}

message();
// end of script

<script type="text/javascript" src="somescript.js">
</script>

Javascript has:

  1. Variables: var x=5; y = 10; var z;
  2. Arithmetic, Assignment Operators
  3. Comparison operators: ==, ===, <, >, ≤, ≥, !=
  4. if, if else statements
  5. switch case statements
  6. Popup boxes with alert(), Confirm boxes with confirm(), Prompt boxes with prompt()
  7. Functions: function funcname(var1, …, varN) { … code … }, Function Calls: funcname(1,2,”abcd”)
  8. Loops: for (var = startval; loopcondition; loopincrement) {}, while (loopcondition) {}, do {} while (loopcondition)
  9. Break and Continue
  10. Array iteration loops: for (var1 in arrayObj) {}
  11. Array Objects: var myfruits = new Array(); myfruits[0] = “Watermelon”;
  12. Events can trigger Javascript: Page (onLoad, onUnload), Form Fields (onFocus, onBlur, onChange), Form (onSubmit), URLs (onMouseOver, onMouseOut)
  13. Exception Handling: try … catch, throw
  14. Special Characters (use backslash): single quote, double quote, ampersand, backslash, new line, carriage return, tab, backspace, form feed
  15. String properties: var t1 = “Hello”; t1.length; t1.toUpperCase(); t1.toLowerCase(); t1.match(); t1.replace(); t1.indexOf(); t1.big(); t1.bold(); t1.strike(); t1.sub(); t1.fontcolor(“green”); t1.fontsize(10); t1.link(“some url”); t1.blink()
  16. Date properties: var d1 = new Date(); d1.getTime(); d1.setFullYear(); d1.toUTCString(); d1.getDay(); if (d1 > d2) …
  17. Show a running clock:
    <html>
    <head>
    <script type="text/javascript">
    function startTime()
    {
    var today=new Date();
    var h=today.getHours();
    var m=today.getMinutes();
    var s=today.getSeconds();
    // add a zero in front of numbers<10
    m=checkTime(m);
    s=checkTime(s);
    document.getElementById('txt').innerHTML=h+":"+m+":"+s;
    t=setTimeout('startTime()',500);
    }
    
    function checkTime(i)
    {
    if (i<10)
      {
      i="0" + i;
      }
    return i;
    }
    </script>
    </head>
    
    <body onload="startTime()">
    <div id="txt"></div>
    </body>
    </html>
    
  18. Boolean objects: var flag = new Boolean(0);
  19. Cookies: document.cookie = “new cookie”;
  20. Timer: setTimeout(“code to run”, delayinmsec);

Members/Properties

this // Window
this.variables  // access variables defined in your javascript scope

document.location // URL for the document

Written by curious

June 27, 2010 at 11:58 am

Posted in javascript