Saturday, June 18, 2011

Left Nav Toggle hide/show in SharePoint 2010 using javascript

You can add this script to master page to provide functionality throughout. Two main pieces which drives this are :

1. JavaScript ( to be placed in head tag )
2. HTML control/element to trigger the call to JavaScript function
3. JavaScript ( to be placed at the end of the page, so that it can execute on page load )

JavaScript( this will go in head tag ):

<script type="text/javascript" >
function getCookie(Name) {

var re = new RegExp(Name + "=[^;]+", "i"); //construct RE to search for target name/value pair
if (document.cookie.match(re)) //if cookie found
return document.cookie.match(re)[0].split("=")[1] //return its value
return ""
}
setCookie = function setCookie(name, value) {

document.cookie = name + "=" + value + ";path=/" //cookie value is domain wide (path=/)
}

function togglefn() {

var e = document.getElementById('s4-leftpanel');

var e1 = document.getElementById('MSO_ContentTable');

if (e.style.display != "none") {

setCookie('showLeftNav', 'no');
e.style.display = "none";
e1.style.marginLeft = "10px";
}
else {
setCookie('showLeftNav', 'yes');
e.style.display = "block";
e1.style.marginLeft = "155px";
}
}
</script>


HTML element ( some where in body tag):

<a href="javascript:togglefn();">hide/show</a>

JavaScript( this will go towards page end ):

<script type="text/javascript" >
var persistedLeftNav = getCookie('showLeftNav');

if (persistedLeftNav == 'undefined') {

setCookie('showLeftNav', 'yes');
}
else {
if (persistedLeftNav == 'no') {
togglefn();
}
}
</script>

1 comment:

  1. I am trying to create a page in sharepoint for my team to use for referencing information. I would like the page to load collapsed with general subject and they can click to open or re-close sections as needed. If your post above will allow me to do this then i am missing something.

    I have permissions to the subsite i am working on as well as access to share point developer 2010. If i create a regular page and add this code in, most of it is truncated when i save and close. I have tried adding it to txt files then calling them from web parts and that does not work either.

    Any thoughts on what i'm missing?

    ReplyDelete