I came across an instance the other day where I had a set of links; some of which where internal, while others where external. I wanted the internal links to open in the same window(target="self"), and the external links to open in a new window/tab(target="blank"). Since I was loading these links from an external json file, populated dynamically and displayed in Flash via a loop, the easy solution to determine the window target was to search for the internal domain name substring within the url string using String.search().
String.search is a handy method that:
Searches for the specified pattern and returns the index of the first matching substring. If there is no matching substring, the method returns -1.
So great for finding the index of a substring, and since it returns -1 if no substring is present, can also be very useful to determine whether substring does not exists.
A quick example looks like:
var s:String = "yoururlhere.com"; var uri:String = "http://www.urlyouarechecking.com"; // check to see if var s can be found in var uri, meaning it has an index > -1. // if so, the window target equals self, otherwise, target = blank. var win:String = ( uri.search( s ) != -1 ) ? "_self" : "_blank"; // within you button code navigateToURL( new URLRequest( uri ), win );
For sake of simplicity, I'm not going to display my exact code as I don't want to go into parsing json in this post. The following is a dumbed down example.
var uris:Array = new Array( "http://www.mikethenderson.com",
"http://www.theonion.com",
"http://www.mikethenderson.com/about/",
"http://mikethenderson.com/inspiration/" );
var s:String = "mikethenderson.com";
var i:int = -1;
var l:int = uris.length;
var xpos:int = 0;
var pad = 5;
var win:String;
while( ++i != l ) {
// create button
var foo:MovieClip = new MovieClip();
foo.graphics.beginFill( 0x6699ff );
foo.graphics.drawRect( 0, 0, 25, 25 );
addChild( foo );
// position foo
foo.x = xpos;
xpos += foo.width + pad;
// assign url to foo
foo.uri = uris[ i ];
// add events
foo.addEventListener( MouseEvent.CLICK, onMouseClick );
foo.buttonMode = true;
}
function onMouseClick( evt:MouseEvent ):void {
// determine if window target should equal self or blank
win = ( evt.currentTarget.uri.search( s ) != -1 ) ? "_self" : "_blank";
navigateToURL( new URLRequest( evt.currentTarget.uri ), win );
}
Leave a Reply