Wednesday 7 August 2013

Navigating to different URL from Desktop and Mobile View in SharePoint 2013

Recently, while incorporating device channels in SharePoint 2013 Online site, I came across a requirement where users were to be navigated to different pages for a particular menu item in the Top navigation. We were using Managed Metadata Navigation and the Top Navigation that was getting rendered was same for both desktop and mobile view. Since it was all dynamic so as per my understanding the option we had was to change this navigation at runtime on the fly. Out of various options that might be available for this, the simplest to me seemed to be dynamically change the URL using Jquery and CSS. I did some analysis as to how the navigation is getting rendered in the Mobile and what classes are getting attached and based on that came up with the following solution 




If you look at the above code snippet which I see for my mobile device channel, every menu item , irrespective of the first level of navigation or the second level of navigation, renders as an li tag with an anchor tag. The anchor tag is having class as level1 for First Level of navigation and level2 for Second Level of navigation. Now, we can play with level1 or level2 class based upon which level of navigation we want to change and hence achieve the desired functionality.

$(".level2:Contains('Menu Item Title')").each(function () {

                    var menuItem = $(this);
                    var parentItem = menuItem.closest("a");
                    parentItem.attr("href", "Desired Navigation Url");


});

Now, what the above code snippet does is that it checks for all the menu items where the title exists that I need to change and for that menu item, it changes the href attribute to the desired navigation url. This code snippet can be placed in the mobile master page for the device channel.

Please note that the above approach is a workaround only and not a perfect solution as there are some side effects of this approach. The above jquery will fire everytime the page loads as we have written it in the masterpage and on the fly it will change the navigation url if we are using the mobile master page. Also, since these classes are OOB so if in future Microsoft changes the class names then this will not work and we need to change it accordingly. However, we can try to explore more around SharePoint ASP menu and try to apply some custom class there and see how that works. Also, for readers who want to explore more options can try to play around with taxonomy using ecmascript and see what can be achieved using that. Above approach is a quick fix and used with caution.

Happy Reading :)




No comments:

Post a Comment