Forum Moderators: open

Message Too Old, No Replies

JS REL + TARGET for XHTML Strict

Setting TWO or more targets for REL in JS

         

JAB Creations

6:28 pm on Feb 5, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hey everyone!
I found this nifty script that will let you set the target of a frame using REL. However I have three frame targets I want to use and I can't seem to get them all working! Could someone please point out what I did wrong because I know I did something wrong! :D

function externalLinks() {
if (!document.getElementsByTagName) return;
var anchors = document.getElementsByTagName("a");
for (var i=0; i<anchors.length; i++) {
var anchor = anchors[i];
if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "external")
anchor.target = "_blank";
else if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "mplayer")
anchor.target = "mplayer";
else (anchor.getAttribute("href") && anchor.getAttribute("rel") == "border")
anchor.target = "border";
}
}
window.onload = externalLinks;

Bernard Marx

7:13 pm on Feb 5, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



That was a cheeky one.

For a while I was thinking "nothing wrong here". It works in IE & Firefox.
It turns out that all the new windows were getting the same name ('border').

You've missed out the

[red]if[/red]
on the last
[blue]else[/blue]

Meanwhile, I did an alternative version (less if..else -ing)

function externalLinks()
{
if (!document.getElementsByTagName) return;
var anchors = document.getElementsByTagName("a");
var map = {external:"_blank", border:"border",mplayer:"mplayer"};
var anchor, i, target;

for (i=0; anchor=anchors[i++];)
if( anchor.getAttribute("href") && (target=map[anchor.getAttribute("rel")]))
anchor.setAttribute("target", target);

}
window.onload = externalLinks;

JAB Creations

7:19 pm on Feb 5, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Thanks, I'll try that out ... though I did get it to work correctly on my site using else if.

If you go to my personal site (link in profile) you can test it in home/music/any playlist that has a hifi or lofi link and a secret egg in philosophy/articles at the top.

Check it out...

function externalLinks() {
if (!document.getElementsByTagName) return;
var anchors = document.getElementsByTagName("a");
for (var i=0; i<anchors.length; i++) {
var anchor = anchors[i];
if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "external")
anchor.target = "_blank";
else if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "mplayer")
anchor.target = "mplayer";
else if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "border")
anchor.target = "border";
}
}
window.onload = externalLinks;

BTW yours works nicely too! :-)