Thursday, September 06, 2007

Make Selected Links in a Links List Open in a New Window


One of the questions that comes up frequently in our classes is, "How can I make some of my links in a Links List open in a new window?" I usually explain how I would accomplish this using JavaScript. I've answered this question so often now that I guess it's time to post the solution here on the blog.

When you add a link to your SharePoint navigation, or in a Summary Link Web Part, it gives you the option to, "Open link in new window." However, the standard Links list, doesn't give you this option. Many users seem to want it though.

The first part of my solution involves training your end-users to add something extra onto links that they want to open in a new window. I like to have them add. "#openinnewwindow". There is a two-fold reason for this. One, it's fairly easy for most users to remember once they've used it a couple times. Two, if the JavaScript code isn't in place, it doesn't cause any errors when a user clicks on the link--it will just open in the same window as normal (unless there is a named anchor on the target page named "openinnewwindow", which is highly unlikely. :) )



The second part of my solution is the JavaScript code that makes this work. Here is the code. It can be placed into the source of a Content Editor web part, or even added to your master page.

Note: In the code example below, replace the square brackets around the SCRIPT tags with angle brackets. If I included the angle brackets, the browser tried to execute the code. :(

[script language="JavaScript"]

//add an entry to the _spBodyOnLoadFunctionNames array

//so that our function will run on the pageLoad event
_spBodyOnLoadFunctionNames.push("rewriteLinks");



function rewriteLinks() {

     //create an array to store all the anchor elements in
the page

     var anchors = document.getElementsByTagName("a");

     //loop through the array

     for (var x=0; x<anchors.length; x++) {

     //does this anchor element contain #openinnewwindow?

          if (anchors[x].outerHTML.indexOf('#openinnewwindow')>0)
{

              
//store the HTML for this anchor element

               
oldText = anchors[x].outerHTML;

              
//rewrite the URL to remove our test text and add a target instead

              
newText = oldText.replace(/#openinnewwindow/,'" target="_blank');

              
//write the HTML back to the browser

              
anchors[x].outerHTML = newText;

         
}

    
}
}

[/script]





That's all you need to do make this work!



For all you code junkies, I think the comments in the code explain well enough what is going on. Let me know if you have questions.