Saturday, February 19, 2011

JavaScript: Open Links In A New Window

Again, I got a little problem at work. Someone decided that it would be funny to "play" with the settings. So: We aren't able to open links in a new window, which kinda like sucks often.

Here's the code, again with an explanation below.


<script language="JavaScript">
_spBodyOnLoadFunctionNames.push("rLink");
function rLink()
{
    var anchors = document.getElementsByTagName("a");
    for (var x=0; x<anchors.length; x++)
    {
      if (anchors[x].outerHTML.indexOf('#onw')>0)
      {
        oldText = anchors[x].outerHTML;
        newText = oldText.replace(/#onw/,'" target="_blank');
        anchors[x].outerHTML = newText;
      }
    }
}
</script>
What's going on there?
This part, "_spBodyOnLoadFunctionNames.push("rLink");" , makes sure that the function "rLink" will be loaded when the page is opening.
First off all "var anchors = document.getElementsByTagName("a");" we are searching for all links and are writing them into our array "anchors".
Now we have to search through the array for our tag, which in this case is "#onw".
If a link got that tag, this little friend will do the trick:

oldText = anchors[x].outerHTML;
newText = oldText.replace(/#onw/,'" target="_blank');
anchors[x].outerHTML = newText;

We are now saving the link into another variable "oldText", than we just cut off our tag and open the link in a new window.

But remember: if you want to open a link in a new window, you have to but the "#onw" tag behind that link.

No comments:

Post a Comment