Thursday, May 13, 2010

Start JavaScript When Page Loads

window.onload = initShowHideDivs;

Monday, May 10, 2010

JavaScript set Opacity

Setting opacity in JavaScript is very simple - except for a bunch of crap you have to add for Internet Explorer to work.
//Note: 0 is completely transparent, 1 is completely opaque.

//see if browser is IE
msie=false;
if (navigator.appName== "Microsoft Internet Explorer") msie=true;

function setOpacity( id, value){
var e = document.getElementById(id);  //store object reference in e
if(msie) e.style.filter = 'alpha(opacity='+ value * 100 + ')';  // for IE
else e.style.opacity= (value);  //all other browsers
}

JavaScript Timing Events

Wohoo! JavaScript has the equivalent of onEnterFrame and setTimeout! Here is a timer that you can start or stop (I got this from here):
<html>
<head>
<script type="text/javascript">
var c=0;//counter
var t;//timer object
var i=1000;//interval (1000 is one second)
var timer_is_on=0;//boolean on/off switch

function timedCount()
{
document.getElementById('txt').value=c;
c=c+1;
t=setTimeout("timedCount()",i);
}

function doTimer()
{
if (!timer_is_on)
  {
  timer_is_on=1;
  timedCount();
  }
}

function stopCount()
{
clearTimeout(t);
timer_is_on=0;
}
</script>
</head>

<body>
<form>
<input type="button" value="Start count!" onClick="doTimer()">
<input type="text" id="txt">
<input type="button" value="Stop count!" onClick="stopCount()">
</form>
</body>
</html>

Adding Content Dynamically

document.write("This sentence gets added to the web page");

Calling an Element by Name

document.getElementById("b1").src ="b_blue.gif"

JavaScript Events, Event Handlers, and Methods

Just like ActionScript, JavaScript has events. Here is an introductory list:
onClick
onMouseOver
onMouseOut
Here is a page that covers it all and how they work in different browsers.
And here is a page for iPhone events

A Simple Button Click Function Call

Step 1. Put a function anywhere between the HEAD tags of your web page:
<script type="text/javascript">
  <!–
    function helloWorld() {
      alert(‘Hello World!’) ;
    }
  // –>
  </script>
Step 2. Somewhere between the BODY tags, make a button that calls the above function.
<input type="button" id="hello-world2" value="Hello" onClick="helloWorld();" />