Scrolling with jQuery

I was creating a photo gallery and wanted to show a few pictures at a time. Then when you hit the next button it would scroll over one picture at a time. I found these plugins for jQuery called serialScroll and scollTo that work great. Plus I added fancybox to it so you could click on the picture to see the full size image.

This is basically how you should have the html set up. Basically what you need to have is an outer wrapper div with the width set to how wide you want the actual gallery. You need to set the overflow to hidden so we only see a few pictures at a time. The next thing is the element that will contain the scolling elements. In this case, the scrolling elements are the “li” tags which are wrapped in a “ul” tag. What is important here is to set a width for the ul tag. If you set a width that is less than the width of all the scrolling elements then they will wrap to the bottom which doesn’t look good. So you can calculate what the width of all the scolling elements are going to be and then set it or just set a really high number if you know that the width of all the elements wont be larger than that.
Another thing to note here is that I wrapped all the image tags in “a” tags with a class=’sidegroup’. This isn’t required for the scolling but is used for fancybox.


<div id='photoprev' style='float:left; cursor:pointer;' >Previous</div>
<div id='photos' style='float:left; width:260px; height:90px; overflow:hidden;'>
  <ul id='innerphotos' style='margin:0; padding:0; list-style:none; width:2000px; padding-left:10px;'>
    <li style='float:left; margin:0 10px; text-align:center; width:100px; height:110px;'>
      <a class='sidegroup' href='photos/341.jpg'>
        <img src='photos/thumbnails/341.jpg'  />
      </a>
    </li>
  </ul>
</div>
<div id='photonext' style='float:left; cursor:pointer;'>Next</div>
<div style='clear:both;'></div>

This is the javascript to initialize the scolling and the fancybox. To see a list of what each option will do click here. There is another option called axis that isn’t mentioned but it will tell the function which way to scoll. Default is ‘xy’ which means it will go down the list in the x direction and then go in the y direction.


	$(document).ready(function(){
		$('#photos').serialScroll({
			items:'li',
			prev:'#photoprev',
			next:'#photonext',
			offset:-5,
			start:0,
			duration:500,
			interval:4000,
			force:true,
			stop:true,
			lock:false,
			exclude:1,
			cycle:true, //don't pull back once you reach the end
			jump: false //click on the images to scroll to them
		});

		$('#photos a.sidegroup').fancybox({
			hideOnContentClick: false,
			zoomSpeedIn:	400,
			zoomSpeedOut:	400
		});
	});

You can view an example of the serial scoll in action here.

Equal Column Heights with Divs using CSS or jQuery

I am not a huge fan of using tables, in fact, most front end projects I do I usually use divs just because I think they’re nicer to look at than tables. So recently I needed to display some data in a table format which means I needed a way to make all the columns in each row the same height. There are a few different ways to do it without using tables.
One of the ways that I don’t like is faux columns. Basically this is just using a repeating background image to give the illusion of equal height columns.

Another way that is rather nice is using jQuery. All you need to do is include jQuery and a plugin called ‘equal heights’. Then include the following code. The “row1” is the class name that you’ll give each of the columns in row one.


$(document).ready(function(){
    	$(function(){
    	    $('.row1').equalHeight();
   	});
    });

The html of it would look something like this.


 <div class='row1'>
   lLorem ipsum dolor sit amet, consectetur adipiscing elit. <br/> Ut aliquet
 nulla eu felis. Donec porta <br/>
    aliquam ipsum. In ac nibh. Nunc dictum. Curabitur rhoncus facilisis nunc.
  </div>
  <div class='row1'>
   lLorem ipsum dolor sit amet, consectetur adipiscing elit. <br/> Ut aliquet
   nulla eu felis. In ac nibh. Nunc dictum. Curabitur rhoncus facilisis nunc.
  </div>
  <div class='row1'>
  	This is some text.
  </div>

And that is it besides styling each div however you want.

A lot of people might not want to include the javascript or just rather not use javascript to change the height of a div. So another way equal columns can be done is by setting a very high padding for each div and then setting the margin to be negative that. You need to wrap a div around it setting the overflow to hidden. Plus if you want borders around each row you won’t be able to set the border-bottom any more so you can simply set the border-top for each one and then add a border-bottom to the wrapper div.


<div id='row_wrapper' style='float:left; overflow:hidden;
                 border-bottom:1px solid black;'>
    <div id='column_1' class='other'>  lLorem ipsum dolor sit amet, consectetur adipiscing elit.
       <br/> lLorem ipsum dolor sit amet, consectetur adipiscing elit.
    </div>
    <div id='column_2' class='other'>  lLorem ipsum dolor sit amet,
       consectetur adipiscing elit.<br/>lLorem ipsum dolor
    </div>
    <div id='column_3' class='other'> lLorem ipsum dolor </div>
    <div id='column_4' class='other' style='border-right:1px solid black;'>
     lLorem ipsum dolor
    </div>
    <div style='clear:both;'></div>
</div>
    <div style='clear:both;'></div>

View the example of using both jQuery and just CSS here

PHP Menu with jQuery Drop Down

I wanted to create a menu where each menu could have submenus. I wanted a way where I could keep adding more submenus very easily. Also when a you are on a page it would be selected and all the parent menus would still stay selected. I decided to make a function to recursively go through an array to create the menu.

I started out with an array() like this.

$tabs = array(“page.php”=>”Page Name”, “page2.php”=>”Page Two”,
“page3.php”=>”Page Three”, “page4″=>”Page Four”);

This is very simple to go through but lets say Page Two has submenus and those submenus have submenus. So I would set it up like this.

$subpage[‘Subpage 2’] = array(“subpg3.php”=>”Sub Sub Page”);
$page2[‘Page Two’] = array(“subpage.php”=>”Subpage Name”, “subpage2.php”=>$subpage);

$tabs = array(“page.php”=>”Page Name”, “page2.php”=>$page2,
“page3.php”=>”Page Three”, “page4″=>”Page Four”);

So now when you’re looping through all the $tabs you’ll need to loop through the $page2 array() as well and then the $subpage array and take the keys for each of the submenus to set the name for the parent menu. Also if I am on subpg3.php I still want to keep “Subpage 2” and “Page Two” selected.

Another thing is if we don’t want to show the page name in the menu but we still want the parent menus selected. All we do is set the value to “HIDDEN” like so:
$subpage[‘Page Two’] = array(“profile.php”=>”Profile”, “profile_edit.php”=>”HIDDEN”);

So here is the function to get all the tabs.

First I declare some variables.
The global $filename could simply be $_SERVER[“PHP_SELF”]. but I personally like to use preg_match to get only the filename since $_SERVER[‘PHP_SELF’] will return the filename along with any subfolder its in. So I do

preg_match("/.*\/(.*)/", $_SERVER['PHP_SELF'], $name);
$filename = $name[1];

The global $dropdown is used to store all the submenus. I used this with jquery to create dropdown menus. If you dont want dropdowns then you can disregard anything commented for dropdowns.

The $found gets set to 1 as soon as the $filename matches one of the tabs.
The $menu is the menu that gets returned. The menu gets returned in an array format like this:
$menu[0] = array(“Home”=>”<a href=’home.php’ class=’selected’>Home</a>”, “About”=>”<a href=’about.php’ >About</a>”);
$menu[2] = array(“test”=>”<a href=’test.php’ class=’selected’>Test</a>”);

you need to do a ksort on menu to make it go $menu[0], $menu[2], $menu[4] instead of $menu[0], $menu[4], $menu[2];


function recursive_tabs($tabs, $row=1){
    global $filename;
    global $dropdown;
    static $found=0;

    $row = $row-1;
    $menu= array();
    foreach($tabs as $key=>$tab){

I check to see if $tab is an array; if it is and $found == 0 then I go into this “if statement” which calls this function again.

     
        if(is_array($tab) && !$found){
            $row = $row+2;
            $submenu = recursive_tabs($tab, $row);

            $tabkey = array_keys($tabs[$key]);

The next block is used for the dropdown array. We need to get all the keys of the $submenu. We need this to match up the $dropdown array correctly with its parent’s row. And then we need the keys of $tabs to match up the $dropdown with the name of its parent.
For example: if the $menu was
$menu[0] = array(“Home”=>”<a href=’home.php’ class=’selected’>Home</a>”, “About”=>”<a href=’about.php’ >About</a>”);

and $menu[0][‘Home’] had submenus then the dropdown would be $dropdown[0][‘Home’] = array(0=>”<a href=’drop.php’>Drop</a>”); so that they match up.


            $subkeys = array_keys($submenu);
            $sizeofkeys = array_keys($subkeys);

            $tabkeys = array_keys($tabs);

            if($subkeys[0]+1 == $row){
                foreach($submenu[$subkeys[0]] as $skey=>$sval){
                    $dropdown[$subkeys[0]-2][$tabkeys[0]][] = $sval;
                }
            }

if the $row is not 0, 2, 4, etc.. then I want to go ahead and return the $submenu.


            if($row%2 != 0  && $row !=0){
                return $submenu;
            }

Next I need to set the row back to the previous number. Then if the filename matches the current tab I loop through the submenu and set it to the menu. Also I check to see if $tabkey[0] == ‘HIDDEN’. $tabkey[0] is the name of each file. If it equals HIDDEN I don’t store it in the menu array but the parents of it will still be selected.
If it is not found I simply add the current $key to the menu.


            $row = $row -2;
            if($filename==$key) $found = 1;
            if($found){
                foreach($submenu as $subkey=>$sub){
                   $menu[$subkey] = $sub;
                }
                if($tabkey[0] != "HIDDEN"){
                   $menu[$row][$tabkey[0]] = '<a class="selected"
                      href="'.$key.'">'.$tabkey[0].'</a>
                }
            }else{
                if($tabkey[0] != "HIDDEN")
                   $menu[$row][$tabkey[0]] = "<a
                        href='$key'>".$tabkey[0]."</a>";
            }

If $tab is an array but $found == 1 I go into this one.


        }else if(is_array($tab)){

            $tabkey = array_keys($tabs[$key]);
            if($tabkey[0] != "HIDDEN")
                $menu[$row][$tabkey[0]] = "<a href='$key'>
                      {$tabkey[0]}</a>";

This next block is for the dropdown menu. Same thing we used above.


            $row = $row+2;
            $submenu = recursive_tabs($tab, $row);

            $subkeys = array_keys($submenu);

            $tabkeys = array_keys($tabs);

            if($subkeys[0]+1 == $row){
                foreach($submenu[$subkeys[0]] as $skey=>$sval){
                    $dropdown[$subkeys[0]-2][$tabkeys[0]][] = $sval;
                }
            }
             $row = $row -2;

The last block is if $tab is not an array. If the $filename == $key then I set $found = 1 and also a change the class to “selected”.


        }else{
            if($filename==$key){
              if($tab != "HIDDEN"){
                $menu[$row][$tab] = '<a class="selected"
                                       href="'.$key.'" >'.$tab.'</a>
              }
              $found = 1;
            }
            else {
                if($tab != "HIDDEN")
                $menu[$row][$tab] = "<a href='$key'  >$tab</a>";
            }
        }
    }
     return $menu;
}

That’s it. Here is all the code together. If you want to see how to use this menu to create a drop down menu keep reading.


function recursive_tabs($tabs, $row=1){
    global $filename;
    global $dropdown;
    static $found=0;

    $row = $row-1;
    $menu= array();
    foreach($tabs as $key=>$tab){
        if(is_array($tab) && !$found){
            $row = $row+2;
            $submenu = recursive_tabs($tab, $row);

            $tabkey = array_keys($tabs[$key]);
            $subkeys = array_keys($submenu);

            $tabkeys = array_keys($tabs);

            if($subkeys[0]+1 == $row){
                foreach($submenu[$subkeys[0]] as $skey=>$sval){
                    $dropdown[$subkeys[0]-2][$tabkeys[0]][] = $sval;
                }
            }
            if($row%2 != 0  && $row !=0){
                return $submenu;
            }

            $row = $row -2;
            if($filename==$key) $found = 1;
            if($found){
                foreach($submenu as $subkey=>$sub){
                   $menu[$subkey] = $sub;
                }
                if($tabkey[0] != "HIDDEN"){
                $menu[$row][$tabkey[0]] = '<a class="selected"
                                      href="'.$key.'" >'.$tabkey[0].'</a>
                }
            }else{
                if($tabkey[0] != "HIDDEN")
                    $menu[$row][$tabkey[0]] = "<a
                                     href='$key'>".$tabkey[0]."</a>";
            }
        }else if(is_array($tab)){
            $tabkey = array_keys($tabs[$key]);
            if($tabkey[0] != "HIDDEN")
                $menu[$row][$tabkey[0]] = "<a href='$key' >
                                                          {$tabkey[0]}</a>";

            $row = $row+2;
            $submenu = recursive_tabs($tab, $row);
            $subkeys = array_keys($submenu);
            $tabkeys = array_keys($tabs);

            if($subkeys[0]+1 == $row && $row>2){
                foreach($submenu[$subkeys[0]] as $skey=>$sval){
                    $dropdown[$subkeys[0]-2][$tabkeys[0]][] = $sval;
                }
            }
             $row = $row -2;
        }else{
            if($filename==$key){
              if($tab != "HIDDEN"){
                 $menu[$row][$tab] = '<a class="selected"
                                             href="'.$key.'" >'.$tab.'</a>
              }
              $found = 1;
            }
            else {
                if($tab != "HIDDEN")
                  $menu[$row][$tab] = "<a href='$key' >$tab</a>";
            }
        }
    }
     return $menu;
}

Once this function returns we’ll need to loop through all the menu’s.

This first thing I do is create an array of divs to wrap the menus in. This is used for styling.


$subdiv[0] = "<div id='toplinks_css'>";
$subdiv[1] = "<div id='sublinks_css'>";
$subdiv[2] = "<div id='sublinks2_css'>";

So as I’m looping through each of the menu items I add a wrapper div around each of them with a unique ID so it can be used with the jquery drop down. The drop down is also wrapped in this div. I also wrap a div around just the link. This is so jquery can can change the style of just that link if you wanted.
The next thing is if there is a drop down menu to add a wrapper around it with position of relative. This will allow each of the drop downs to be positioned under their parent menu. I then wrap the drop down in another div with a unique Id used by jquery and a class called dropdown. The main thing that you need to have in this class is position:absolute, display:none; and z-index:999 (“some number to make sure drop down goes on top”).


$head .= "<script type='text/javascript'>
$(document).ready(function(){";
$count = 0;
foreach($menu as $key=>$tabs){

$str .= $subdiv[$i];
foreach($tabs as $tkey=>$tab){
  $str .= "<div id='header$count' style='float:left; margin-left:20px;'>
       <div id='head$count'>$tab</div>";
  if($dropdown[$key][$tkey]){
     $str .= "<div style='position:relative;'>
                     <div id='dropdowncontainer$count' class='dropdown'>
                         <div class='inner'>";
     foreach($dropdown[$key][$tkey] as $dkey=>$dval){
       $str .= $dval;
    }
$str .= "</div>
</div>
</div><div style='clear:both;'></div>";
}

The next bit is the jQuery. I use a jQuery plugin called hoverIntent which allows you to set a time that the mouse must be over the link before it will execute. This way if you’re just moving the mouse across the page the drop down wont show up. It takes two functions. The first one is on hover and the second is off hover.


$head .= "$('#header$count').hoverIntent(function(){
    $('#head$count a').css('background-color','#0167B1');
";

   if($dropdown[$key][$tkey])
     $head .= "$('#dropdowncontainer$count').show();";
$head .= "    },

  function(){
    $('#head$count a').css('background-color','');";
    if($dropdown[$key][$tkey])
    $head .= "        $('#dropdowncontainer$count').hide();";

$head .= "  });  ";

$str .= "</div>";
$count++;
}
$str .= "<div style='clear:both;'></div></div>";
$i++;
}
$head .=   "});
</script>";

And that will give you a dropdown box which you can now style however you want.

Click here to view the example.

Cross Domain Scripting using Flash

I was building a site for a client when I came across this cross domain security issue. My client had users that needed to be able to send data from their website to my clients server which would process the data and return a new set of data to replace the old. I couldn’t just make an ajax call since the browser wont allow you to receive data from another server. My options to get around this were that I could use iframes or use flash. I decided to go with the flash for no particular reason.

I’m going to go through each file I created. First I’m going to go through the .fla file and then the two .as files and then the javascript file.

I am using Flash 8 and actionscript 2.

To start, create a new .fla file.

Import the following class to allow flash and javascript to communicate.


import flash.external.ExternalInterface;

Flash wont allow you to access another domain without adding the following code. The ‘*’ will allow all domains to be able to access the file on your server or you can add individual domains.


System.security.allowDomain("*");

I create a new instance of DebugHelper which is created in a separate .as file which I’ll show later. This is only used to help me print out text to test the code. It creates a text field and then when you call the Log function will print out the string you pass to it.


var deb = new DebugHelper();
DebugHelper.Log("test");

This is a button I created in the .fla. When it is clicked it loads the policy file. This is an xml file that tells the flash which domains are allowed to access the files that are in the same folder the xml file is in and all subfolders on your server. You can use a ‘*’ to allow all domains. The ExternalInterface.call calls a javascript function which takes the content of the webpage and passes it to flash.


The crossdomain.xml file
<?xml version="1.0"?>
   <!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/
dtds/cross-domain-policy.dtd">
   <cross-domain-policy>
       <allow-access-from domain="www.company.com" />
       <allow-access-from domain="*" />
   </cross-domain-policy>

btn.onRelease = function() {
  System.security.loadPolicyFile("http://yourdomain.com/crossdomain.xml");
  var successful = ExternalInterface.call("sendit");
};

This next bit allows the flash element in javascript to send data via the function “sendData” which calls the “xmlhttp” flash function. Then this function creates a new HttpConnection object which is in another .as file which I’ll explain later. You pass to it the filename of where you want to send the data. You then can set the body with the data you passed to the function and whether you want to use POST or GET. I then add the onData event handler to the object so I know when I get data back from the server. When that is fired I set the data to a variable called retText and then pass it to javascript with the call “setData”.


ExternalInterface.addCallback("sendData", this, xmlhttp);
function xmlhttp(body:String) {
	var http = new HttpConnection("http://yoursite.com/crossdomain.php");
	http.setAction("POST");
		http.setBody(body);
		http.setContentType("application/x-www-form-urlencoded");
		http.onData = function(src:String) {
				_root.retText = src;
				ExternalInterface.call("setData", "retText");
		};
		http.send();
}

This last function calls the javascript function “storageOnLoad” so we know the flash is loaded.


var ret = ExternalInterface.call("storageOnLoad");

This next bit is the DebugHelper.as file. This just creates a text field that allows me to call Log() on DebugHelper to help me debug by printing out text to the screen.


class DebugHelper {
	static var log:String;
	static var debug:Boolean;
	function DebugHelper() {
		_root.createTextField("tf", 0, 0, 0, 315, 238);
		log = "";
		var ret;
		_root.tf.text = "Running Flash version: "+getVersion();
		DebugHelper.Debug();
	}

	public static function Debug() {
		debug = true;
	}
	public static function Log(input:String) {
		log = log+" ___ "+input;
		if (debug) {
			_root.tf.text = input+"\r"+_root.tf.text;
		}
	}
}

This next file is the HttpConnection.as file. I start out by defining some variables and functions. The sendAndLoad and Load functions I set to the default LoadVars.prototype.sendAndLoad and LoadVars.prototype.load function which allows me to send this objects data to the given url using the LoadVars class.


 class HttpConnection {
	private var action:String = "POST";
	private var body:String = "";
	private var url:String = "";
	var contentType:String;
	var sendAndLoad:Function = LoadVars.prototype.sendAndLoad;
	var load:Function = LoadVars.prototype.load;
	// note: many headers can't be added. http://livedocs.macromedia.com/
       //   flash/8/main/wwhelp/wwhimpl/common/html/
       //   wwhelp.htm?context=LiveDocs_Parts&file=00002324.html
	var addRequestHeader:Function = LoadVars.prototype.addRequestHeader;
	var onData:Function;

This function creates an instance of this class.


	function HttpConnection(_urls:String) {
		url = _urls;
	}

The next four function allow me to set the url, action, body and contentType.


	function setUrl(_urls:String) {
		if (_urls) {
			url = _urls;
		}
	}
	function setAction(_action:String) {
		if (_action) {
			action = _action;
		}
	}
	function setBody(_body:String) {
		if (_body) {
			body = _body;
		}
	}
	function setContentType(_contentType:String) {
		if (_contentType) {
			contentType = _contentType;
		}
	}

This function is overriding the default toString() function. This automatically gets called when the sendAndLoad function is called. If I wasn’t using an object to call the sendAndLoad function I would have to create an instance of LoadVars and set the variables like this:

var my_lv:LoadVars = new LoadVars();
var result_lv:LoadVars = new LoadVars();
my_lv.id=10;
my_lv.text = “some text”;
my_lv.sendAndLoad(url, result_lv, ‘POST’);

The toString() function would get called to convert my_lv to “id=10&text=some+text”. Since I already have the body in that format I don’t need to do that so I just return the body.


	function toString():String {
		return body;
	}

This is the function that sends the data to the server.


	function send() {
		DebugHelper.Log("HttpConnection send this(action="+action+")");
		// note: if we did a sendAndLoad on a GET, the Flash API would add
                //a question mark '?' at the end of the querystring

		if (action == "GET") {
			load(url);
		} else {
			sendAndLoad(url, this, action);
		}
	}
}

Now the javascript file.

I create a javacript object to hold the flash.


var FlashObject = new Object();
FlashObject.height = 138;
FlashObject.width = 215;

This function will check to see if the flash is installed.


FlashObject.isFlashInstalled = function() {
	var ret;
	if (typeof(this.isFlashInstalledMemo) != "undefined") {
            return this.isFlashInstalledMemo;
        }
	if (typeof(ActiveXObject) != "undefined") {
  	   try {
		var ieObj = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
	    } catch (e) { }
	     ret = (ieObj != null);
	} else {
		var plugin = navigator.mimeTypes["application/x-shockwave-flash"];
		ret = (plugin != null) && (plugin.enabledPlugin != null);
	}
	this.isFlashInstalledMemo = ret;
	return ret;
}

This simply gets the flash element.


FlashObject.getFlash = function() {
	return document.getElementById("flash");
}

This function will write the flash object on your page. For me, I needed to send the entire content of the body to flash and then replace it without replacing the flash object. So I needed to add a wrapper div around the entire content of the body. That way when I get the data back from flash I would replace everything inside that wrapper div. This will keep the flash from getting over written which can cause some errors. If you don’t need to replace the entire page then it’s not necessary.


FlashObject.writeFlash = function() {
	var swfName = "http://yourdomain.com/crossdomain.swf";
	if (window.ActiveXObject && !FlashObject.isFlashInstalled())
	{
	  // browser supports ActiveX
	 // Create object element with
	 // download URL for IE OCX
	 document.body.innerHTML="<div id='wrapperdiv'>"+document.body.innerHTML+
                                                    "</div>";
	 document.write('<object classid=
                           "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"');
	 document.write(' codebase="http://download.macromedia.com');
	 document.write('/pub/shockwave/cabs/flash/swflash.cab#version=8,5,0,0"');
	 document.write(' height="'+this.height+'" width="'+this.width+'"
                                   id="flash">');
	 document.write(' <param name="movie" value="' + swfName + '">');
	 document.write(' <param name="quality" value="high">');
	 document.write(' <param name="allowScriptAccess" value="always">');
	 document.write(' <param name="swliveconnect" value="true">');
	 document.write('<\/object>');
	}
	else
	{
	 // browser supports Netscape Plugin API
	 document.body.innerHTML="<div id='wrapperdiv'>"+document.body.innerHTML+
                                           "</div>";
         document.write('<object id="flash" data="' + swfName + '"');
	 document.write(' type="application/x-shockwave-flash"');
	 document.write(' height="'+this.height+'" width="'+this.width+'">');
	 document.write('<param name="movie" value="'+swfName+'">');
	 document.write('<param name="quality" value="high">');
	 document.write('<param name="swliveconnect" value="true">');
	 document.write('<param name="pluginurl"
                    value="http://www.macromedia.com/go/getflashplayer">');
	 document.write('<param name="pluginspage"
                     value="http://www.macromedia.com/go/getflashplayer">');
	 document.write(' <param name="allowScriptAccess" value="always">');
	 document.write('<p>You need Flash for this.');
	 document.write(' Get the latest version from');
	 document.write(' <a href="http://www.macromedia.com/software/
                                    flashplayer/">here<\/a>.');
	 document.write('<\/p>');
	 document.write('<\/object>');
	}
}

The next few functions are used to load up the flash.


FlashObject.load = function() {
	if (typeof(FlashObject.onload) != "function") { return; }

	if (FlashObject.isFlashInstalled()) {
		// if we expect Flash to work, wait for both flash and the document to be loaded
		var finishedLoading = this.flashLoaded && this.documentLoaded;
		if (!finishedLoading) { return; }
	}
	// todo: cancel timer
	var fs = FlashObject.getFlash();

	if ((!FlashObject.isFlashInstalled() || this.flashLoaded) && fs) {
		if (FlashObject.checkFlash()) {
			callAppOnLoad(fs);
		} else {
			callAppOnLoad(null);
		}
	} else {
		callAppOnLoad(null);
	}

	function callAppOnLoad(fs) {
		if (FlashHelper.onloadCalled) { return; } // todo: figure out why this case gets hit
		FlashHelper.onloadCalled = true;
		FlashHelper.onload(fs);
	}
}

function storageOnLoad() {
	FlashObject.flashLoaded = true;
	FlashObject.load();
}

This function is nice because if you already have a window.onload event and need to add more onload events this will add them.


FlashObject.addLoadEvent = function(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			oldonload();
			func();
		}
	}
}

This initializes the flash object variables and onload functions. If you wanted the flash to automatically run on page load you could simply add the function call (in this case “sendit()”) inside the onload function.


FlashObject.init = function() {
	this.flashLoaded = false;
	this.documentLoaded = false;
	// attach to the window.onload event
	this.addLoadEvent(onload);
	function onload() {
		FlashObject.documentLoaded = true;
		FlashObject.load();
	}
}

FlashObject.init();

The function that actually gets the data you want to send and then calls the flash function “sendData”.


 function sendit() {
    var body = 'uid='+testdata;
    body += '&pagetext='+
       encodeURIComponent(document.getElementById('wrapperdiv').innerHTML);
    FlashObject.getFlash().sendData(body);
 }

When the data gets returned it stores it in a variable which we set in the http.onData function. We then pass the name of the variable to this function and call GetVariable which returns the data.


function setData(varname){
	var str = FlashObject.getFlash().GetVariable(varname);
	document.getElementById("wrapperdiv").innerHTML = str
}

And finally this writes out the flash object to the page.


FlashObject.writeFlash();

Now all anyone would need to do would be to include this javascript file at then end of their page right before the body tag.

Here are the .fla, .as and .js files.
CrossDomain.zip