2007-05-26

Use PHP to create JavaScript on-the-fly

One possible approach to writing JavaScript on-the-fly

The idea behind this technique is that the javascript, which is stored in a PHP array named $js_array, can expand and contract as needed, depending upon the current php html output in any particular page.

My technique uses a singular file, which i call dochead.inc in which this javasript array is tested for value each time a page is viewed. If it has value, or if there are more dimensions created of this multidimensional array, i am required to do no manipulation of external script files, or rewrite the < script > code in the html header-- the PHP array takes care of all of it for me.

the code from that dochead.inc file, might look like this:

(NOTE: as you might extrapolate, the technique can be applied to CSS as well.)

<link rel="stylesheet" href="<?php echo $stylesheet; ?>" type="text/css" />

<?php

if(isset($js_array)){
 foreach($js_array as $jsDkey => $jsDynamic){
  print $jsDynamic;
 }
}

if(isset($cssArray)) {
 echo '<!-- CSS ARRAY -->';
 $csi=0;

 foreach($cssArray as $newArray){
 $newCss[$csi]=$newArray;
 $csi++;
 }

 $csx=0;
 foreach($newCss as $cssArryOut){
  echo $newCss[$csx];
  $csx++;
 }
}
else {
 echo '<!-- CSS ARRAY HAS NO VALUE -->';
}


?>
</head>

$js_array=array(); $js_array['open']="<script type=\"text/javascript\"> \n"; $js_array['hideManForm']="function hideManForm(obj) { \n".  "var el = document.getElementById(obj); \n".  " if ( el.style.display != \"block\" ) { \n".  " el.style.display = \"block\"; \n".  " } \n".  " else { \n".  " el.style.display = \"none\"; \n".  " } \n".  "} \n"; $js_array['close']="</script> \n";

No comments: