Archive

Posts Tagged ‘script’

Display JavaScript Source Programatically

March 23rd, 2009 Tech 2 comments

If you are running a JavaScript example page you can use the following function that will take the last script element on the page and print it out in a code tag. It uses JQuery to do the work, so you will need to include that library before using this function.

<script type="text/javascript">//<![CDATA[
 function displaySource(name) {
  $('<code>'
   + $('#display-' + name).prevAll('script').eq(0).html()
   .replace(/^\s*|\s*$/g, '')
   .split('\n').slice(1, -1).join('\n')
   .replace(/(^|\n) /g, '$1')
   .replace(/('[^']*')/g, '<em>$1</em>')
  + '</code>')
  .insertAfter('#display-' + name);
 }
//]]></script>

The function works by selecting the current script tag and finding all script elements before it. It then selects the first one it finds and outputs the contents to a code tag. It uses a few regular expressions to convert some of the characters to a more human readable format. The function is called like this.

<script type="text/javascript" id="display-test">displaySource("test");</script>

JS Bin

March 12th, 2009 Tech No comments

JS Bin is an online tool that allows you to test JavaScript without having to muck about with files. You can just quickly cut and paste some code in and view the output. It is even possible to make the code you are looking at public and then use this as part of an ajax call in another instance of the application.

To get you started there is a nice help section, which also includes a couple of videos.

JS Bin

This tool really impressed me, especially the easy inclusion of several different JavaScript frameworks. I don’t mind testing JavaScript, but sometimes I just want to run a little bit of code on it’s own to see why it isn’t working as I expected it would. This tool fills that much needed gap, and the addition of allowing other people to view your code is a very nice feature. Well worth a look!

Typewriter Script

February 3rd, 2009 Tech 2 comments

The following script can be used if you want to simulate a typewriter in an element on screen. I have put in a lot of comments to describe what is happening but the script works by taking each array element in turn and adding it character by character to the content of the selected element.

<script type="text/javascript">
// set up text to print, each item in array is new line
var aText = new Array(
"line 1",
"line 2",
"line 3",
"line 4",
"line 5",
"    ",
"line 7",
"line 8",
"THE END "
);
var iSpeed = 100; // time delay of print out
var iIndex = 0; // start printing array at this posision
var iArrLength = aText[0].length; // the length of the text array
var iScrollAt = 20; // start scrolling up at this many lines
 
var iTextPos = 0; // initialise text position
var sContents = ''; // initialise contents variable
var iRow; // initialise current row
 
function typewriter()
{
 sContents = ' ';
 iRow = Math.max(0, iIndex-iScrollAt);
 var destination = document.getElementById("typedtext");
 
 while ( iRow < iIndex ) {
  sContents += aText[iRow++] + '<br />';
 }
 destination.innerHTML = sContents + aText[iIndex].substring(0, iTextPos) + "_";
 if ( iTextPos++ == iArrLength ) {
  iTextPos = 0;
  iIndex++;
  if ( iIndex != aText.length ) {
   iArrLength = aText[iIndex].length;
   setTimeout("typewriter()", 500);
  }
 } else {
  setTimeout("typewriter()", iSpeed);
 }
}
</script>

You can run this script by either including an onload attribute in the body tag, or by placing a call to the typewriter() function after the element that you want to use to fill the text with.

<div id="typedtext"></div>
<script type="text/javascript">typewriter();</script>

Randomising The Middle Of Words In PHP

November 18th, 2008 Tech No comments

I was sent an email the other day that contained some text were the start and end letter of each word were left alone, but the middle of each word was randomized. The weird part was that the text was still readable, which is due to the way in which the brain processes words.

I wondered if I could replicate this using a PHP script. All I would need to do is split apart the sentence into the component words and loop through those words, randomizing the middle of them. Clearly, it is not possible to mix up the order of letters in a word less than four characters long so a check would be needed for this. This is what I cam up with:

function mixWordMiddle($string)
{
 $string = explode(' ',$string);
 foreach ( $string as $pos=>$word ) {
  $tmpArray = array();
  if ( strlen($word) > 3 ) {
   $chars = preg_split('//', $word, -1, PREG_SPLIT_NO_EMPTY);
   for ( $i = 1 ; $i < count($chars)-1 ; ++$i ) {
    $tmpArray[] = $chars[$i];
    shuffle($tmpArray);
   }
   $string[$pos] = $chars[0].implode($tmpArray).$chars[count($chars)-1] .' ';
  }
 }
 echo implode(' ',$string);
}

I then tried plugging in the following text about evolution.

$string = 'In biology, evolution is the changes in the inherited traits of a population of organisms from one generation to the next. These changes are caused by a combination of three main processes: variation, reproduction, and selection.';

And came up with something like the following.

In bliygoo, eoutivoln is the cganhes in the iethirned titras of a piaplouotn of oargnsims form one gneoeatirn to the nxte. Thsee cagnhes are ceusad by a cmibitoonan of there main persocses: voaitanri, rteunodpoirc, and stoneleic.

Which is actually quite difficult to read. I thought that this might be because I had used a bit of text with too many long words, so I selected another:

$string = 'A giant Saudi oil tanker seized by pirates in the Indian Ocean is nearing the coast of Somalia, the US Navy says.';

This produced the following text.

A ganit Suadi oil taeknr seezid by ptaiers in the Ianidn Oecan is nraneig the cosat of Smiolaa, the US Navy syas.

This is just a test script, so it doesn’t take into account any punctuation. However, the text it produces is still difficult to read, which leads me be skeptical of the claims of that the email I received.

Categories: PHP Strings Tags: , , , , , ,

External Script Files And Printing Objects With Flex

November 6th, 2008 Tech No comments

Yesterday I talked about using the Flex Script element to run code within the mxml file, you can also use the source attribute of the Script element to reference external files. To create an external script file FlashDevelop go to the File->New and select Blank Document. You can also do this by pressing Ctrl+N. This will create a blank document that you must save into your src folder of your project with the extension as. Note that if you call this file sourcefile.as then you must reference this in your script tag like this.

<mx:Script source="sourcefile.as">

</mx:Script>

When you do this you will notice that the script file will be part of the Main.mxml file. You can add functions in the same way as you would with an inline script tag.

Printing

With this external script file we will now create some images and print them using the built in printing object that Flex has. This object is called FlexPrintJob and you must include this at the top of your script file if you want to use it. Put the following line at the top of your script file.

import mx.printing.FlexPrintJob;

Create a button in your mxml file that will be used to print.

<mx:Button id="print" label="Print" click="printImage();" />

Add in an image that will be printed.

<mx:Image source="one.png" id="one" />

Here is the image that will be used.

Flex test image

Flex test image

Go back into the script file and add the function that will print the image out. We called this function printImage() in our Button declaration. This function works by creating a new FlexPrintJob object called printJob. This function start() is then used to try and print. Basically, this function returns true if the print job worked, and false if the user clicked cancel.

If the start() function returns true then the object to be printed (in this case the image with the id of "one" is added to the printJob object. Finally, the send() function is called which sends the data off to the printer. Here is the function.

public function printImage():void
{
 // Create a FlexPrintJob instance.
 var printJob:FlexPrintJob = new FlexPrintJob();
 
 // Start the print job and check that it worked
 if (printJob.start() != true) {
  return;
 }
 
 // add object to be printed to the print job
 printJob.addObject(one);
 
 // send to printer
 printJob.send();
}

This is the simplest use of the FlexPrintJob function as there are controls that can be used to format the pages.

It is possible to print off multiple objects, especially if they are children to another object, by adding the parent object to the FlexPrintJob object. Take the following section of mxml, which defines a Canvas element, with three positioned images as children.

<mx:Canvas id="images">
 <mx:Image source="one.png" id="one" x="0" y="0" />
 <mx:Image source="two.png" id="two" x="100" y="0" />
 <mx:Image source="three.png" id="three" x="0" y="100" />
</mx:Canvas>

This produces the following application.

Three images in a canvas

Three images in a canvas

To print out all three images at once just include the Canvas object instead of the single image object. Change line 11 in the printImage() function from this:

 printJob.addObject(one);

To this.

 printJob.addObject(images);

The printJob object knows about inheritance and will print out everything contained within that element. This includes buttons or any other element that you put into the canvas element.

See the Flex documentation for more information about the FlexPrintJob object.