1,804 articles and 14,810 comments as of Friday, April 29th, 2011

EndUserSharePoint has combined resources with NothingButSharePoint.com. You can now find End User (Mark Miller), Developer (Jeremy Thake) and IT Pro SharePoint (Joel Oleson) content all in one place!

This site is a historical archive and is no longer being updated. Please update your favorites, bookmarks and RSS feeds.

NothingButSharePoint.com
Thursday, July 16, 2009

Dynamically Show/Hide Multiple Web Parts

July 21, 2009 Update: We have updated the script based upon user feedback. Please let us know how it goes.

Bryon Wyly writes Codeless Solutions for SharePoint. In this article he’s written a really fun script, demonstrating how to show or hide multiple lists and web parts. It’s like a magic trick – now you see it, now you don’t. And the solution is very easy. Thanks Bryon!

Show-Hide Multiple Web Parts

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.

 

Show-Hide Multiple Web Parts

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

 

Show-Hide Multiple Web Parts

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

 

Show-Hide Multiple Web Parts

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 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 easily 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 their 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:

<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>

var displayFirst=true 			// Show the first web part on load
var menuTitle="Web Services Tasks" 	//Title of the menu for the links
var keyWord="Tasks"
//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*/

$("document").ready(function(){
  {$("#jLoadDiv").append("<p class='ms-WPHeader'><H3 class='ms-standardheader ms-WPTitle'>"+menuTitle+"</h3></p>")}
  hideZones(1,true);
});

function show(item)
{
 hideZones(0,false); //hide all web parts
 document.getElementById(item.id).style.display=""; //Show selected web part
}

function hideZones(writeMenu,displayFirst)
{
	var menu=""
    var editString = "Add"
    editString = editString + ' a Web Part'
    var isEditMode = $("td:contains(editString):not('editString')");// checks to see if in edit mode
    var listTitle = $("td:contains('"+keyWord+"')");//make an array of the titles of the web parts
    isEditMode.length=0

    $.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 (isEditMode.length==0 && displayFirst==false)
		{
		  document.getElementById(wpnum).style.display="none";
		}
		else
		{
		  displayFirst=false;
		}
		menu=menu+"<li><a href='javascript:show("+wpnum+");'>"+listZone.title+"</a></li>"
		}
	});
    if (writeMenu==1){$("#jLoadDiv").append("<ul>"+menu+"</ul>")}
} //end function
</script>

The code has three options:

  1. var keyWord=”Tasks” – Put the keyword thats in all your web part titles here
  2. var displayFirst=true – Leave this true if you want the first web part to show up on load
  3. 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).

Bryon WylyGuest Author: Bryon Wyly

Bryon has been a Microsoft Developer for 6 years and is currently the SharePoint developer and administrator for the Xavier University. He is responsible for SharePoint collaboration sites, CIO dashboards and the campus wide intranet.

Bryon enjoys finding solutions with SharePoint that an end user can implement out of the box or with SharePoint Designer.

 

Please Join the Discussion

63 Responses to “Dynamically Show/Hide Multiple Web Parts”
  1. David Milliken says:

    Will this work on a Data View Web Part that was created in SPD?

  2. David – Just curious… how else are you going to create a DVWP? — Mark

  3. JB-Mids says:

    Wow, this is absolutely brillient… I’ve had the requirment for this on more than one occasion and could only think to mess about with i frames and page viewer parts etc and in the end I may as well not have been using sharepoint at all lol..

    This is such a simple, and yet powerful solution… Thanks for sharing!

  4. Nancy says:

    This looks great. I can see immediate use for such a solution across the board.

    One question- do the target web parts HAVE to default to “show title” for this to work?

  5. Karthik says:

    This is really a innovative task!!!

    I tried to use your code to accomplish this task on couple of Excel Web Parts, but not luck. It just showed me the menuTitle and did not created dynamic menus. Also Excel web parts are not hidden even having the keyword in their title.

    Will it work only for list web parts? I could not understand how to debug it?

  6. sireesh says:

    Hi Bryon

    Its great to see the code that exactly matches my requirement, however when i tried to replicate, it hides all the webparts and displayed the only first one, but in content editor webpart it just displayed the menu title and not the dynamic menu..

    I tried to dig the solution but no use…

    can you please tell me what might got wrong from my side.

    Thanks in Advance

  7. sireesh says:

    Hi Bryon

    I found the reason why the menu is not displaying.

    Hi Karthik

    I hope this will help you

    replace the code
    menumenu=menu+”<a href=’javascript:show(”+wpnum+”);’”+listZone.title+”“;

    with

    menu=menu+”“+listZone.title+”“;

    the colse tag for the is missed in the above code.

    Replace this
    editStringeditString = editString + ‘ a Web Part’

    with

    editString = editString + ‘ a Web Part’

    Hope this will help…

    Thanks
    Sireesh

  8. sireesh says:

    menu= menu + ” ” + listZone.title + ” “;

    put > in between ‘(single quot) and “(double quot) that comes after this (”+wpnum+”);

  9. Kermmit says:

    I love the idea but can not get the code to work. Could someone send me or post the full working code. Thanks

  10. Karthik says:

    Sireesh,

    I appreciate your reply. I did what you mentioned in your comments … But no luck … is this working for you with those changes?

    Now my menu title also not showing up… I am checking whether I missed something.

    Please let me know if you feel that I missed something.

  11. Bryon says:

    I believe that the code may gained a special character when pasted from it’s original source.

    Try pasting from the original blog post http://wyly.wordpress.com/2009/05/22/showhide-multiple-web-parts/ … Make sure that the Title and the keyword as the same including capitalization. I will look through both sets of code and see why the code on my post works and the copied code on endusersharepoint.com does not.

    Bryon Wyly

    PS I used the default master template and this code has been tested and confirmed on lists and document libraries.

  12. I have updated the script. Please confirm it is now working. Thanks. — Mark

  13. Bryon says:

    Ok, I copied the code above and it now works, thanks Mark!

    Remember that the keyword has to exist in the title of all the web parts you want to show up in the menu.

    You change the title of the menu with the vaiable menuTitle

    Bryon

  14. Karthik says:

    Bryon, Its working now, Thanks.

    Actually I tested this script on Dundas chart web parts for SharePoint. But its not working as that of other out of the box SharePoint web parts.

    I included a keyword in 3 of the dundas charts, the menu list is not showing up. If I give the full web part name as keyword then it is showing only that menu item in menu list.

    I think I need to make some workarounds to make this work.

    Do you have any thoughts on this?

  15. Karthik says:

    Whenever I am placing a keyword in script for dundas charts, its showing me an error on the page in status bar of IE.

    How to debug the code to exactly know what the error on the page is?

  16. Kermit says:

    Thanks so much. It works!

  17. Nancy says:

    I have deployed this with “var displayFirst=false” to hide all the associated web parts on page load. However, I cannot get the first web part to stop displaying.

    It is my understanding, from your explanation, that if “false” is present in this line, none of the web parts shold be seen until a user clicks a link.

    Am I missing something?

  18. Bryon says:

    Nancy,

    Found it!

    hideZones(1,true);
    needs to be changed to
    hideZones(1,displayFirst);

    It will then work correctly, I’ve submitted some revised code to fix this and a Firefox only issue I have encountered.

    Thanks for all your feed back!

    –Bryon

  19. JB-Mids says:

    Hia,

    Copied the code from the link above and it worked great 1st time… However only when in draft page mode, as soon as I publish a page it displays all webparts again.

    Any ideas? I wanted this primarily for our main intranet pages which are all publishing sites.

    Thanks :-)

  20. Bryon Wyly says:

    JB,

    I tried out the javascript code in a publishing template and it worked as a draft and and after being published. The only reason I could think of why it was not working is that perhaps the code in the content editor web part was not published with web parts.

    Could you look for the code in the view source. If the code is there, it could other javascript code on the page or something in your master template.

    Email your view source code of the draft mode and the published version if you would like my help. I would be very curious to resolve this issue.

    Bryon

  21. Bill Corrigan says:

    Great code, thank you very much for it.

    One problem I am having is I get a security warning about content not being delivered using a secure HTTPS connection. Is this due to this line:
    var jQPath=”http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/”;

    -Bill

  22. AutoSponge says:

    @Bill,

    Point your browser to http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js and download the code. Then upload it to a document library on your SSL server where everyone has (at least) read access.

    Now, alter the jQPath variable with the new directory (e.g., if you added the file to the /js library, your new path is “/js/”.

  23. James Shidell says:

    Bryon -

    This is great. However, I was wondering if this can be down with just web parts and no lists?

    Is there a way to create the menu dynamically with just using webparts?

    Thanks,

    JShidell

  24. Bryon Wyly says:

    This should work with any web part James as long as you put the keyword in the title of each web part you want to show/hide and appear in the menu.

    I HAVE only tested it on task lists and document libraries though. The code hides all the web parts with the specified keyword in the title then populates the menu with the title of any web part it hides. Hope this helps, let me know what other types of web parts you try!

    Bryon

  25. James Shidell says:

    Bryon -

    Thank you. I got it to work just on web parts. I’ve only tried them on CEWP and Image Web parts. But I’m pretty sure they will work for others as well.

    Only thing I need to figure out now is a unique title identifier because not all Web Parts are related to each other but I would like to use your Hide/Unhide code on all Web Parts regardless if they relate to each other or not.

    Also do you know of any way to dynamically change just one CEWP based off of another?

    For example if I had one CEWP that displayed a map of Africa, and I had another CEWP that lists the countries in Africa I would like to just click on the country name in the second CEWP and it would change the map in the first CEWP to the map of that specific country?

    I only ask because what I’m trying to accomplish something like this, and I would like to just have one CEWP that would change instead of having 15 different CEWPs and hiding and unhiding them. The site would become very cluttered.

    Thanks again for your help, and again thanks for sharing.

    v/r
    JShidell

  26. Bill Corrigan says:

    I have successfully used it on lists with views and Excel Web Access.

    Also I solved my https problem by adding the s to the http before the link to the library at Google.

    -Bill

  27. JB-Mids says:

    ps: works on all webparts, regardless of whether it’s a list, doc library… a wss3 webpart or 2007 webpart or a webpart created in sharepoint designer.

    RE: The Publishing Page issue:

    This seems to have resolved itself and the javascript now works well on all publishing pages on Moss 2007, the previous issue I had may have been because I was playing with it over citrix at the time via the web rather than our internal network.

    Improvement: I have gone further and hidden the ‘Web Part Tasks links’ webpart that is created automatically and simply copied the hyperlinks to a really neat css hover menu.

    One last Question Though!

    The script is reliant on the ‘TITLE’ of the webpart being shown on the web part view. This is not desirable in my particular application so is there a way of hiding the title by maybe making it ‘white text’ ie: show it but have it appear as invisable by assigning the color white?

    I guess this could be a style sheet thing that I’d have to consider against the entire site collection so before I go that route, is there a way of doing that via the code directly?

  28. James Shidell says:

    Is there any way this can be done on more than just one web part?

    If I have say 4 web parts that contain information that relate to each other is there a way to hide/unhide them all based off the title?

    I’m guessing no because the way this script works is it hides all web parts with the same title expect the first one. If all 4 web parts have the same title it will hide 3 out of the 4 web parts. I would like to show all 4.

    Can this be done?

    v/r
    JShidell

  29. Karthik Nallajalla says:

    James,

    I think this script don’t exactly works for your requirement, but you can create your own script by referring this as an example for your requirement.

    or else you can manually show/hide web parts using some if … else conditions in javascript in content editor web part or a form web part

  30. Jamie Tomlinson says:

    Sorry if this is off topic but I have a feeling that what I want to do could be achieved with some slight changes to the code on this page. I have created mutiple web parts for a page and have setup connectors between them. Does anyone know if there is a way to hide the consumer web parts until the relevant provider has ‘provided’ a value? I have found the visibility filter web part but am not the SP admin so cannot deploy a package. Any thoughts would be greatfully received.

    TIA,

    JamieT

  31. rameshusa says:

    Thanks for the excellent work. I tried with Header, Footer, 2 Columns, 4 Rows Layout. Added 2 webparts to the 1st Row. The easy tab picked up the names and showed the tabs properly.

    However, Only on the last tab all the details are displayed. When I click on 1st tab nothing happens. 2nd tab (This case the last one too!), both webparts details are display.

    Can you take a look or let me know what i am doing wrong?

    Thanks,

    • Karthik Nallajalla says:

      So you added a content editor web part and pasted the above Jquery or Javascript then assigned some value to the keyword variable in the Javascript. Then you added two web parts in a row (side by side) and also included the value of the keyword in title of the two added web parts.

      Did you do same as I mentioned above? If you did the same steps and if it don’t work. Try to keep the web parts in same web part zone (vertical). Let me know even if it don’t work.

      • rameshusa says:

        Yes, the issue is exactly as you mentioned.

        Yes, it works for vertical web parts placed within a same or separate web part zone.

        In my case,
        I have to show (Say All(NY), All(NJ), All(CT) in the 1st row,
        Then Male(NY), Male(NJ), Male(CT) in the second row,
        Female(NY), Female(NJ), Female(CT) in the third row.

        I have created web parts to show all the employees in the 1st row, based on the states, 2nd row, Only Male employees based on the state and the 3rd one Female employees based on the state.

        In this case, if I arrange all the 3 web parts in column layout, it works out fine. However, when I place them on a row web part, I am experiencing the issue mentioned earlier.

        Let me know if you find any fix.

        Thanks,

        Ramesh

  32. rameshusa says:

    i am really sorry, the issue is related to easy tab and not show/hide web parts.

    Sorry folks, Please move this easy tab folder if you could.

    Thanks,

    Ramesh

  33. Anand says:

    This is a great artilce, I have also same requirement and I am very new to sharepoint can any one give me detail about this. If we need to use content editor webpart what is the html code we need to add.
    Looking forward for your help.

    Regards
    anand

    • Anand – I have updated the article to include display of the code you are looking for. — Mark

      • Anand says:

        Thanks for your reply Mark,

        I got the javascript code but not the html code to add in content editor web part. I need that code to, please help me regarding this.

    • rameshusa says:

      When you place a content editor web part, you have to click on edit the webpart, then on the right side if you scroll you will see the 2nd button which will say (I think) source editor or something like that. ( I do not have access to sharepont now – once in my office, i will send the exact name). Click on the button will popup editor screen, where you will have to cut and paste the code.

      Hope it helps,

      ramesh

      • Anand says:

        Thanks Rameshusa,

        The question I am asking here if we see the screen shot we have Overdue task, My Task,
        High Priority Task,
        All Task hyperlink, In the code I didn’t find these names, can you please share those also.

      • rameshusa says:

        I just confirmed it it is SOURCE EDITOR. For finding out where he is using Tasks…Just look up and read under

        The code has three options:

        He has defined 3 items there. In the code also, you will see these right after tag..

        Hope it helps.

      • Bryon Wyly says:

        Rameshusa,

        The menu options are populated automagically by the code. The code sniffs out all web parts on the page with the key word in the title. It not only hides them, it dynamically creates the menu and the HTML for you as well.

        Just follow the instructions verbatim and you will see how it works.

        Bryon

  34. rameshusa says:

    Hi Anand, It is actually for you. Whatever value you speicify in the keyword is the word the script looks for in the webparts. Below is the clear explanation:

    Read the comments by Bryon Wyly:

    The menu options are populated automagically by the code. The code sniffs out all web parts on the page with the key word in the title. It not only hides them, it dynamically creates the menu and the HTML for you as well.

    Just follow the instructions verbatim and you will see how it works.

    Bryon

    Thanks Bryon it is for anand.

  35. ven says:

    I would like to add an image instead of , but when i add it doesn’t seem to work. can you tell me how to add in hte code line menu=menu+”“+listZone.title+”

    • Karthik Nallajalla says:

      Hello Ven,

      I could not understand what you exactly what to do, you would like to add an image instead of?

      I am just guessing, are you trying to have an image in menu items instead of title?

    • Bryon Wyly says:

      Ven,

      I have tested this on a image web part and it worked. If that is what you are doing and it is not working, double check that the key word is in the title and that the word is capitalized correctly, if you are still having issuesm let me know exactly what they are.

      Bryon

  36. ARicco says:

    Has anyone tried the following?: http://spvisibilityfilter.codeplex.com/

    Seems exactly what I need, the ability to programmatically hide and unhide web parts based on web part connection and other parameters. Unfortunately, I’m part of a large organization and getting IT to add this open source web part to our production SharePoint servers is a challenge to say the least.

  37. Scott says:

    I like this code, and got it to work. Was wondering if you might be able to help with some modifications. Basically, instead of just listing out the titles of the web parts in the list, I want it to have the title,and then a short description of the title so you know what you are clicking on. I am trying to use this for a training course listing, so that in the dynamic web part, it would show the title and a short description. When you click on the title, it would then display the hidden web part with the longer description. Any ideas?

  38. Kevin says:

    Byron,
    I got the code to and it works great, but with CEWP it seems to place a description along with the WP Title. Is this unique to this webpart?

  39. Kiernan says:

    Bryon,
    I’ve copied the code and transferred it over to my company’s internal network (intranet) which does not communicate to the external Web. Nothing is working. Is this because it can’t pull the code from the internet?

    Thanks!

  40. Pete says:

    Great post. I was wondering if the same can be achieved if I want to show hide all web parts that are in the list on the left. eg. I show a list that user can have access to: So, user 1 has access to My Tasks, Overdue Tasks — so without having the user click on anything those 2 web parts are shown. Then user2 has access to All tasks, My tasks, Overdue tasks – then those 3 are shown.
    I can get that filtered list by other means and then use your code to show hide web parts.
    Possible?

    • Karthik Nallajalla says:

      Pete,

      You want to show all the web parts on which user have access and to hide the remaining. Is this your questions? If this is your question then you can use “Audience Targeting” on a web part. Then users can see only the web parts they have targeted to.

      Let me know if I did not not answered your question.

      • Pete says:

        No. Target Audience will not work in this case, as for it to work I will have to create multiple groups for each project and each phase, which means 100s of groups. and obviously I dont want to do that. I want to show/hide web parts based on the values in a custom list.

    • Karthik Nallajalla says:

      I don’t think this code works for your scenario. But if you are good in JQuery then you can modify this code to retrieve values from your custom filtered list and compare them with web parts on the page then show or hide them. You can also achieve this by creating a custom web part programmatically.

  41. Altfdorfs says:

    Only seems to work in EDIT mode! And displays both web parts in normal mode. Seems to be working wrong way round.

    • Altfdorfs says:

      Put some code to write out the values of the script and only appears to SEE web parts in EDIT mode, which is why it is only working in EDIT mode. In normal mode it does not see any of the web parts.

      • Altfdorfs says:

        Further to last post. You need to make sure the Web Part Title is displayed in the Web Part properties for this to work.

  42. Janice says:

    This has been a lifesaver. Thank you! Trying to see if there is a way to make this work with multiple keywords for different webparts on the same page. I have been playing around with the code to try and make this work but haven’t been successful. Any help is greatly appreciated.

  43. Bryon Wyly says:

    Janice,

    Are you wanting to have one menu that hides/displays multiple web parts? Or are you wanting to have multiple menus, each menu hiding and showing web parts with a key word?

    I could probably make some quick adjustments so you can use the Hide/Display more than once one the page.

    • Janice says:

      Thanks for your response. I am trying to have multiple menus, each menu hiding and showing web parts with diferent keywords for each. If you could, I would be so happy. I have been struggling with this for the past week now trying to make it work.

Trackbacks

Check out what others are saying about this post...
  1. [...] Dynamically Show/Hide Multiple Web Parts  (29) Bryon Wyly [...]




Notify me of comments to this article:


Speak and you will be heard.

We check comments hourly.
If you want a pic to show with your comment, go get a gravatar!