SharePoint top navigation jQuery re-route

wwwIf you need to add additional URL parameters to a page based on an action, pass a URL parameter from page to page, or you just need to prevent the default action of the navigation bar, using jQuery to accomplish this can help. In the most recent project that we did, we used jQuery to override the top navigation bar in SharePoint to pass along a URL parameter from page to page easily. This helped us use the URL filter for a majority of our web parts on select pages.

My problem was that I couldn’t modify the navigation of the page to dynamically add a particular URL parameter that our web parts would consume. With a combination of the URL filter web part, we are able to change the content of the page based on the URL parameter. We could use cookies to store the value locally on the users’ machines, update the URL each time the page loads, and resets the cookie if a new value is chosen. But the problem with the cookie route was that it took more effort than I wanted.

The option that I chose was to prevent the default link of the top navigation and reload the window with the attached parameter. The top navigation of SharePoint has the class “ms-topNavContainer”, so jQuery is able to target hyperlink click event and prevent the default action.

$(‘.ms-topNavContainer a’).click(function(event) {
event.preventDefault();
});



Using JavaScript and variables, we can grab the current parameter from the current URL.

var cur_url = $(this).attr(“href”);
var cur_para = window.location.search;



We now can replace the current URL of the window to the newly built URL + parameter combo.

window.location.replace(‘http://site’+cur_url+cur_para);



Now all you would need to do is either include this script into a page layout, external JavaScript file, or per page. The main requirement would be to a starting point for a parameter to be placed in the URL.

Full Script:

$(‘.ms-topNavContainer a’).click(function(event) { 

event.preventDefault();

var cur_url = $(this).attr(“href”);

var cur_para = window.location.search;

window.location.replace(‘http://site’+cur_url+cur_para);

});

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.