Show/Hide Multiple Web Parts

Updated to work on SharePoint 2010

You have 4 web parts on the page but when the page loads you only see the first web part, ‘Overdue Tasks’. A dynamically created menu of all the task web parts is on the left.

When you click on ‘My Tasks’, ‘Overdue Tasks’ is hidden and ‘My Tasks’ appears in its place

Clicking on ‘All Tasks’ shows the All Tasks Web part

When you edit the page, you can see all 4 web parts and easily modify or reorder them.

Technical Expertise and Permissions needed:

  • Create views for a list
  • Add and Modify web parts on a page
  • Copy/paste some code into a content editor web part

Here I was again, trying to figure out how to show multiple views of the same list on my page. I had a task list and I wanted to show tasks for the current person (My Tasks), Overdue Tasks, High Priority Tasks and a Final view of all the tasks on the same page.

Problem is, there is a limited amount of real estate on the page to show all these views at once. I have in the past made multiple pages and placed one web part on each and made a menu that allowed me to go back and forth, the only problem is now I have to wait for a page load each time.

Fix:
I need some javascript or jquery to d hide all the webparts and only show me the one web part I want to see. My solution also has to do the following:

  • Be easy used by non-technical users
  • Work no matter how many web parts are included
  • Not hide the web parts in ‘edit page’ mode

Here is what I came up with:

I created views for Overdue Tasks, and High Priority in my task list. (All Tasks and My Tasks are created by default)

I created 4 web parts of the task list in one column on my page. I set there width to 600 px each gave each one a title with the word “Task” in it (my keyword). I set there chrome type to title only and I changed their view to one of the four views I wanted to show.

Next I added a content editor web part and added the following code:

<script type=text/javascript>
////////////////////////////////////////// User Chosen Parameters ///////////////////////////////////////////////
var displayFirst=false // Show the first web part on load
var menuTitle="" //Title of the top menu. If empty, spacing will be removed
var keyWord="Department" //The keyword in the title of all web parts used in this code. ie any web part with the word 'Tasks' will be hidden and added to the menu
var menuType="DropDown" //Enter 'List' or 'DropDown'
//--------------------------------------------------------------------------------------------------------------------------------------------------
</script>

<div class=content id=jLoadDiv></div>

<script type=text/javascript>
if(typeof jQuery=="undefined"){
var jQPath="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/";
document.write("<script src='",jQPath,"jquery.js' type='text/javascript'><\/script>");
}
</script>

<script type=text/javascript>
$("document").ready(function(){
 $("#jLoadDiv").html("");
if(menuTitle!="")
{$("#jLoadDiv").append("<p class='ms-WPHeader'><H3 class='ms-standardheader ms-WPTitle'>"+menuTitle+"</h3></p>")}
hideZones(1,displayFirst);
});

function show(item)
{
hideZones(0,false); //hide all web parts
var webPart
if(menuType=="List"){webPart=item.id}
else if(menuType=="DropDown"&&item!="none"){webPart=item}
else if(menuType=="DropDown"&&item=="none"){return false;}
document.getElementById(webPart).style.display=""; //Show selected web part
}

function hideZones(writeMenu,displayFirst)
{
var menu=""
var menuDD=""
if (displayFirst==false)
{menuDD="<option value='none'>--- Select an Item ---</option>"}
var listTitle = $("td:contains('"+keyWord+"')");//make an array of the titles of the web parts

$.each(listTitle, function(i,e)
{
var listZone=listTitle[i];
var wpnum
if (listTitle[i].title.length!=0){
//slice off the table title and select the web part number
wpnum="MSOZoneCell_WebPartWPQ"+listZone.id.substring(15);
//If not in edit mode, hide the web parts
if (displayFirst==false)
{
document.getElementById(wpnum).style.display="none";
}
else
{
displayFirst=false;
}
var Title=listZone.title.split(" - ")// get rid of the description by splitting on the " - " and only showing the first part
menu=menu+"<li><a href='javascript:show("+wpnum+");'>"+Title[0]+"</a></li>"
menuDD=menuDD+"<option value="+wpnum+">"+Title[0]+"</a></option>"
}
});
if (writeMenu==1&&menuType=="List")
{$("#jLoadDiv").append("<ul>"+menu+"</ul>")}
else if (writeMenu==1&&menuType=="DropDown")
{$("#jLoadDiv").append("<select onchange='javascript:show(this.value)' id='webShowHide'>"+menuDD+"</select>")}
} //end function
</script>

The code has three options:

var keyWord=”Tasks” – Put the keyword thats in all your web part titles here

var displayFirst=true – Leave this true if you want the first web part to show up on load

var menuTitle=”Whatever you want the title of your menu to be”

Viola!
Now the code will go out and add any web part that has your keyword in the title to a menu and then hide it. When you click on the menu item all the web parts will be hidden except for that web part (view).

UPDATE:
1 Fix has been added.
The webpart description has been filtered out so it won’t show up in the menu

There is a new menu type at the type, since several people asked for a drop down instead of a list for the menu.

At the top of the code, change:
var menuType=”List” – to show the menu as a list
var menuType=”DropDown” – to show a drop down list with all your selected web parts

Drop Down Menu

Advertisements

65 Responses to Show/Hide Multiple Web Parts

  1. […] Show/Hide Multiple Web Parts A tutorial on how to to create a view/web part toggle menu in SharePoint […]

    • Scott says:

      Awesome info. I spent hours searching for a solution until I finally found yours. One problem; it is only working in edit mode for me. I first tried this on a test site and it worked perfectly. I then implemented it on a production site whre it only worked in the edit mode. Once I get out of the edit mode the two web parts are displaying and the dropdown contains no entries.

      My keyword is “Prework” and it is the first word in each web part title. I think I am doing this right but need your kind help. Thanks!

  2. Dana says:

    I desperately need to accomplish this same thing – but am definitely not a “techie” person. I can follow all your instructions perfectly – except all of the content editor webpart code is not visible.

    Would it be possible for you to share? This is phenomenal! Thanks for any assistance you can provide.

    • wyly says:

      Dana,

      If you are not seeing all the code, the best option is to ‘select copy to clipboard’ or ‘view plain’ at the top of the code box then copy and paste to your Content Editor Web Part. Hope this helps!

  3. chris says:

    interesting…. a ‘codeless solution’ that requires 30+ lines of javascript. Does ‘codeless’ mean only no server-side code?

    • wyly says:

      Codeless means you don’t have to break out the visual studio and custom create a new web part.

      Just copy and paste some javascript. This means you a: don’t have to know how to code, or b: have any other special permissions other than being able to add a content editor web part to the page.

  4. Matt says:

    I have one list that I made several views out of. I created a webpart page and put your code in a CEWP. My keyword is “Issues” for all of my views and have changed this in your code to reflect that… However, the only thing this code does is put numbers within the CEWP. I see 02. 03. 04. 10. 11. Can you give me any advice?

    • Matt says:

      If you highlight all of the code that’s on the page, it grabs the numbers associated with that line of code too. That was what my problem was and I’d like to thank Byron for helping me with it. One more suggestion, would it be possible to just get the title of the webpart and not the description of the list too? All of my links for the different views work but the links all have the view name – Description of the list. Problem is that it says the same thing many times over and gums up the page a bit. Any fixes for that?

  5. Marz says:

    Hi, when the code is used for displaying an image, it just displays the web part title and its description. The image is not being displayed. How can the code be modified.

    • wyly says:

      Interesting!

      I just tested it on an image and it did work, though I did see the description as well as the title. If it is not hiding/displaying the image for you I would recomend trying another list and see if it’s only the images, because it worked for me. I will make some code that strips the description.

    • wyly says:

      The newest iteration of the code now strips the description from the menu item.

  6. Kenneth says:

    Yippie! I got this working on my first attempt. Thanks! A couple of questions…

    var displayFirst=false doesn’t seem to work. I still get the “first” (alphabetic? or just the first webpart in the zone?) one displayed. Is there something else I need to do to start up with nothing more than the ‘menu’ that your script generates in the content editor webpart?

    Also, the content editor webpart eats up a lot of whitespace on the page. I’ve got Chrome set to Title Only, which works for my needs, but then there is a pretty big white space before the menu draws, and then one after the menu array. I’d like to tighten this up a little. Any suggestions? Better still, any thoughts on how to replace the array menu with a “standard” pulldown? That would take up minimal space, but give me virtually unlimited choices in this feature.

    Thanks again!

    • wyly says:

      The displayFirst=false now works. thanks for bringing that to my attention. The webparts are displayed top to bottom I believe, at least that is how it works for me. you are the second person to suggest the dropdown… It would not be hard, perhaps I will attempt it in the next few days.

    • wyly says:

      All your suggestions are a reality! If you leave the title field blank, the white space will disapear, and you now have an option for a drop down or a list to drive the menu.

  7. Shawn says:

    Is there a way to not show any tasks at all until a task type is selected? That is, is there a way to keep the 4 on the right side hidden until a link on the left is selected?

    • wyly says:

      Yes,

      Find the variable at the top of the script that says:

      var displayFirst=true

      set it to false and nothing will show up till a menu item is selected.

      The default code above should do that. Try coping and pasting it in if you have an older version.

  8. Jono says:

    Excellent Post. Nice work!

  9. Jim says:

    I can’t figure out how to make the drop-down work with the chrome set to “Normal” and “Border-Only” on the webparts. This script works great when I leave the chrome set to default, but all of the web parts on my page need to have borders.

    When in edit mode, the drop-down and script work as if not in edit mode. When exited out of edit-mode, the drop-down is empty, and all webparts automatically appear on the page with borders.

    • wyly says:

      Jim,

      I confirmed part of what you found, here is what you can do:

      When the chrome type is set to “none” or “border only” no title appears. The reason is that this prevents the code from working properly since it looks for a table cell titled with the key word. In the above mentioned chrome types this table cell does not exist since the title does not exist.

      So you must have a title however the boder is optional. If you need a border, select the chrome type “title and border” and the code will work correctly.

  10. Jim says:

    Thank you for this cool script and for your hlpe with it! I am now trying to stretch out its application to include multiple web part zones. I am trying to create a Sharepoint page that has several zones, each containing several web parts. The script works well with the first web part zone, but I can not control different areas of the page independently.

    I have added a separate content editor web part to each web part zone. Each content editor web part contains this script with a different keyword and drop down list relative to its web part zone. However, if I try to make a selection in a drop-down list, it changes the content across zones.

    I am unable to only change the content in the zone that each script resides in. I have tried changing the variable names to make them unique in each zone, but the effect is the same. I have spent a lot of time looking at the code, but I have not been able to determine what I could modify that would make the script web part zone specific.

    • Jim says:

      Nevermind, I figured out my original question. I simply added a “2” to the end of all of the variable names, and it applied only to the current zone. This script works very well!

      • Robert says:

        Hi Jim, you said you got the code to work in multiple zones, Im having an issue with it in multiple zones and multiple content editors, which variables did you need to modify?

  11. DragonDon says:

    Wow, this is the closest I’ve come to finding a solution for my client. They want to hide part of a classified add unless you are e member of the site(paid). Any suggestions for that?

    • wyly says:

      The easiest way i can think of offhand is to use targeted audiences. Create an audience for a group that are NOT members then make the web part only show only to that group.

      Hope that helps!

  12. Doug H says:

    This is an outstanding tool. I was able to follow the steps and have it working just as I needed it to in about 15 mins.

    I do have one question, is there a way to use it twice within the same web part zone? I have two different types of lists that for whic it would be useful, but I can’t seem to get it to work when I add it the second time.

    Thanks for a great solution!

  13. VEN says:

    Can this be applied for document libraries?

  14. Jeremy Menefee says:

    Great job with this code! I have one question that I could defiantly use some help with. I am working on using this code with data from web parts and the issue that I am having is that when I allow the user to insert new items into the web part with the insert link the page refreshes and the java script reverts to the default state (which is not to display the first web part so it is blank). Any ideas on how to get the code to cooperate with me? After I click the insert button and the page refreshes (which reverts to a blank page) I can reselect the web part that I had selected and the insert new item dialog will be there. I need it to remember the selection so that after the insert hyperlink is pressed it will show the insert dialog without having to select the web part from the list again. If you need more information or this was not explained well please email me and I can send you some screen shots that will show what I want to do.

    Thanks for your help!!

  15. Daniel Jarvis says:

    Very nice. This is exactly what I have been looking for for a while and it looks great! How can you modify the code so it can work for other webparts besides listview webparts. I tried it on a graph web part and it didn’t work.

    Thanks!

  16. ChiQua25 says:

    Thanks. This is great. It worked well for me. The one question I have is how to repeat this multiple times on a page? For example, I have multiple webparts where I want to use the “Candidates” keyword and then additional web parts that I want to use the “Tasks” keyword. Any help is very much appreciated.

  17. Larry says:

    Great concept. All the graph slices are the same size. Any thoughts?

  18. Alex says:

    Hello,

    I love this, except that the varDispFirst=false does not seem to be working. My first webpart shows by default, and is NOT included in the list even. So it’s there no matter what other webpart is shown.

    I am using this on SPS 2010 and otherwise, it works fine. Thoughts on the varDispFirst?

    Thanks

    • Alex says:

      I should note that the drop-down works correctly in Edit-Page mode. All webparts are hidden and I have to select which one to show in order to edit.
      Also I changed the http URL to https to avoide https prompts (site is https)

  19. Ojsram says:

    hi Bryon,

    Thanks. this is a great post.
    I am having an issue, when I placed webparts like calendar on the page, the webparts disappear after including the script on the content editor webpart. Is there a way to work with webparts like calendar or library etc.

    Please let me know …thanks

  20. Katie A says:

    This is so close to what I’m looking for! And I’m thinking that if this is possible, then the functionality I need is. I work for a high school and our homepage is run on SharePoint 2007. We have a Content Editor Web Part that is featured on our website that displays our daily bell schedule. However, we have a handful of days throughout the year during which we have late starts and thus our bell schedule is different. So, we created another web part with our late start schedule. Right now, we manually control them, adding one to a page during the late start days and then closing it and adding our regular bell schedule for the other days. I can’t help but think that there is a way to control the opening and closing of these webparts by date. Basically, I want the late start schedule to appear on some pre-determined dates (and the regular schedule web part to close on those dates) then on any other date have the regular bell schedule date stay open. Is this possible with a bit of code?

  21. Nalani Carson says:

    I found this to be the perfect solution to several similar inquiries for our intranet; however, initially it worked fine, but when I made a minor edit to the web part name, everything disappeared. I cannot view anything in Edit Mode except the content editor web part containing the bulleted list; the content editor web part containing the code and the list view web parts related to the menu have all disappeared. If I try to add a new list view web part, it also disappears. Does anyone have any idea as to what is going on and how I can “find” the web parts that disappeared? This will be a huge problem if you cannot make future edits without everything disappearing.

    • wyly says:

      Nalani,

      In order to view the web parts again, delete the content query web part. You can save the contents in in it by going to source – then copying and pasting all the contents into notepad.

  22. Nalani Carson says:

    I finally realized I could bring the page up in SP Designer and edit or remove the offending web part. Now I know two things: 1) do not use the Keyword in the web part title of the content editor web part containing the script or not only do the right column web parts disappear, but also the menu web part 2) to edit one of the hidden web parts, remove the script from the menu/content editor web part and hold it in your clipboard, then save that web part with a blank source editor — the hidden web parts are then visible again and can be edited; as soon as editing is done, paste the script back into the menu/content editor web part.

  23. Nalani Carson says:

    Bryon – after I got my demo page set up, I showed it to my boss and he was very impressed. Thank you so much for sharing this. It is the perfect solution for several issues here. Can this be adapted so that the menu displays like a Table of Contents format — numbering and indenting? Have you ever modified this script like that? Thank you!

  24. Jim says:

    Hey,

    Just wondering if you’ve had a look at this within SP2010? Ive tried it out and it works as expected while in edit mode, but when you save and view the page normally the following line:

    document.getElementById(webPart).style.display=””;

    in the show function doesnt seem to be getting the object passed to it correctly. Any clues? I’ve dabbled in JS a little bit but certainly not with SharePoint much so no clue how the API might have changed!

    • Jim says:

      Oh, and to add. It does work if you use the DropDown style but not the list style. Cheers!

      • wyly says:

        OK, I added a line that prevents the dropdown from repeating in 2010. I’ll check the list styles next.

      • wyly says:

        The changed fixed the List view now.

        Thanks for your input. It’s working for me in 2010 now.

        Bryon

  25. Latte says:

    Works great but can I use this twice one one page with different web part zones? Tried already and it gave an error, it didn’t work on the new web part zone but the dropdown moved to the new (second) CEWP and was displaying there. Refused to create a dropdown for the second web part zone.

    Thanks.

  26. Gemma says:

    Hi Bryon,

    Say if I have two pages. One storing your above code and the temporarily hidden web parts (page A).

    Is that possible to put a hyperlink on a second HTML page which calls on the Javascript function to open a particular hidden web part on page A automatically when clicked?

    Please help.

    Thanks
    Gemma

  27. shivk says:

    Hi.When i tried with performance point webpart. It didn’t work
    How can I use the script for performance point webpart?

  28. Eric M says:

    Hi Bryon, for some reason, your code only works for me if i have 1 item in the list. The minute i have 2 webparts that match.. it shows nothing.

    • Eric M says:

      Bryon, just to give some more clarity, i removed

      document.getElementById(wpnum).style.display=”none”;

      and it is now populating the list properly. But obviously does nothing aside from populate the list as i removed the setting to hidden.

      Not sure why this is causing it to crash out.. any thoughts?

  29. Ahmed Moussa says:

    Works like a Piece Of Cake, you are the man

  30. Charlie says:

    Hi Bryon!

    This is GREAT! Have been looking everywhere for something like this.

    Is there a way to choose one of the options in your drop down list by default when the page initially loads?

  31. Kris says:

    Genius!!! Thanks for this has save me a load of hassle 🙂

  32. Kris says:

    Can anyone help me modify this to show in different web part zones, I have a tabbed page and with zones called Zone Tab 1 etc. and ID = ID2 , tearing my hair out trying to figure this one out, help will be much appreciated 🙂

  33. wyly says:

    Kris,
    This code is designed to go out and search for a key word in the Web part title. If the page has jQuery tab on it, this could conflict with the code, ie not showing the expected web parts in the menu.

    Try using the code on a simple team site page, it should work regardless of the web part zone.

    Let me know what you are using to tab and how it is not working. (Always hiding, always showing, not showing the menu ect)

  34. Kris says:

    Hi Wyly, took your advice and to no avail – made a simple aspx page with 2 webpart zones – added same doc library in each zone but changed view to show different items – added titles ss in first zone webpart and rm in the other, added a CEWP in each zone and added the code with the keyword suitable for each web part, problem is the CEWP in second zone does not show anything and the CEWP in the first zone shows the key work which I added for first zone i.e ss, it seems like the second web part code is overriding the first code

  35. wyly says:

    Kris,
    I double checked and was able to Hide/Show web parts in two different zones. If you need more help with this, send me the script you are using then the names and type of web parts you are using and I’ll see if I can replicate and figure out your issue.

    Bryon

  36. Suganthi says:

    This code works only on webparts, having the chrome type set to show the Title of the webpart. Is there any way to make this work otherwise?

    • wyly says:

      Hmmm, unfortunately not. The title is how it creates the list to show. The chrome type set to none, the title would not be included in the page html.

  37. Andrei says:

    Hi Wyly,

    Can the code be modified so that the menu items are linked images instead of text?
    I have no coding skills so a detailed response would be very helpful.

    Thanks a lot,
    Andrei

  38. Any way to get this to work in SharePoint 2013? My site has been migrated and now this no longer works 😦

  39. Tracey Southall says:

    Hi,

    is there a way to display the links as buttons instead of a drop down or a list?

    Thanks

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: