Adjust the code to enhance the functionality of web components in Sharepoint

I recently came across some code online that I'm trying to modify in order to add an expanding button next to a web part on my Sharepoint site. However, the problem is that by default, all web parts are already expanded and require a click to collapse. The specific web part (FAQ - WebPartWPQ7) I want collapsed initially so users can expand it with just one click. The other web parts do not need this expand/collapse functionality.

<script type="text/javascript">
//
// Toggle Expand/Collapse Buttons
//

function WPToggle(thisId, ImageId) {
    if (document.getElementById(thisId).style.display == "none") {
        document.getElementById(thisId).style.display = "";
        document.getElementById(ImageId).src = "/_layouts/images/minus.gif";
    } else {
        document.getElementById(thisId).style.display = "none";
        document.getElementById(ImageId).src = "/_layouts/images/plus.gif";
    }
}

function ExpandCollapseBody() {
    var i = 1;
    var WPid = "WebPartWPQ1";
    var WPtitleid = "WebPartTitleWPQ1";
    var Toggleid = "ToggleImage1";
    do {
        try {
            document.getElementById(WPtitleid).innerHTML = '<IMG id="' + Toggleid + '" onClick="WPToggle(\'' + WPid + '\',\'' + Toggleid + '\')" alt="Expand/Collapse" style="margin:6px 5px 0px 2px; float:left; cursor:pointer;" src="/_layouts/images/minus.gif" />' + document.getElementById(WPtitleid).innerHTML;
            if (document.getElementById(WPid).style.display == "none") {
                document.getElementById(Toggleid).src = "/_layouts/images/plus.gif";
            }
        } catch (err) {}
        i = i + 1;
        WPid = "WebPartWPQ" + i;
        WPtitleid = "WebPartTitleWPQ" + i;
        Toggleid = "ToggleImage" + i;
    } while (document.getElementById(WPid))
}

_spBodyOnLoadFunctionNames.push("ExpandCollapseBody()");
</script>

Answer №1

To hide the 7th web part, simply add the code

if (i == 7) WPToggle(WPid, ToggleId);
to the initialization function. I made some adjustments to your code using jQuery since you mentioned it in your question:

function WPToggle(thisId, ImageId) {
    var isVisible = $('#' + thisId).is(':visible');
    $('#' + thisId).toggle(!isVisible);

    var img = isVisible ?  'plus' : 'minus';
    $('#' + ImageId).attr('src', '/_layouts/images/' + img + '.gif');
}

function ExpandCollapseBody() {
    var i = 1;
    do {
        var WPid = 'WebPartWPQ' + i;
        var WPtitleid = 'WebPartTitleWPQ' + i;
        var Toggleid = 'ToggleImage' + i;
        var htmlImg = '<img id="' + Toggleid + '" alt="Expand/Collapse" style="margin:6px 5px 0px 2px; float:left; cursor:pointer;" src="/_layouts/images/minus.gif" />';
        var wpTitle = $('#' + WPtitleid).data('idx', i);
        wpTitle
            .html(htmlImg + wpTitle.html())
            .click(function() {
                var idx = $(this).data('idx');
                WPToggle('WebPartWPQ' + idx, 'ToggleImage' + idx);
            });
            if (i == 7) WPToggle(WPid, Toggleid);
        i++;
    } while ($('#WebPartWPQ' + i).length == 1)
}

_spBodyOnLoadFunctionNames.push("ExpandCollapseBody()");

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unexpected behavior occurs when ajax is added to an array for jQuery promise results

In my code, I have an each loop that makes individual AJAX requests and stores them in an array like this: var promises = []; $items.each(function(k, v) { promises.push( $.ajax({ url: ..., .... }) ); }); $.when.app ...

Running npm start in a React development environment on Linux without automatically opening a browser can be achieved by configuring

As I dive into learning React, I've noticed that I keep running npm start in the terminal multiple times. However, it can be quite frustrating how a new browser window opens each time. I'm currently attempting to prevent this from occurring on my ...

Utilize Google's Places Direction API Autocomplete feature to pre-select the starting location

I am currently utilizing draggable markers along with 2 autocompletes to assist with obtaining directions. You can find more information about this setup here: https://developers.google.com/maps/documentation/javascript/examples/directions-draggable. With ...

Adjust the Scope in Angular-Charts.js Post-Rendering

I am currently facing a challenge with displaying multiple charts using the angular-charts.js framework. The issue is that I require all the charts to have the same scale, but each chart currently has its own scale based on the displayed data. Unfortunatel ...

Leveraging AJAX for seamless PHP execution without page refresh

I have this HTML form: <form class="clearfix" method="POST"> <input name="username" type="text" placeholder="Username:"> <input name="password" type="password" placeholder="Password:"> <textarea name="comment" placeholder="Comment: ...

How can I trigger a CSS animation to replay each time a button is clicked, without relying on a timeout function?

I am having trouble getting a button to trigger an animation. Currently, the animation only plays once when the page is refreshed and doesn't repeat on subsequent clicks of the button. function initiateAnimation(el){ document.getElementById("anima ...

The JSON file gets emptied every time I refresh the page repeatedly

I am encountering an issue where my JSON file gets cleared if I restart the page quickly after using the fs module to read/write it. The JSON data is read at the beginning of the page like this: let preferencesJSON; try { preferencesJSON = fs.readFile ...

Getting started with Babylon.js using npm: A step-by-step guide

I recently posted about my struggles with setting up Babylon.js using npm on Stack Overflow. Since I haven't received any answers yet, I was hoping to rephrase my question: Can someone provide a detailed step-by-step guide on how to set up Babylon.js ...

Product pages created with PHP, such as displaying as: Page: [1] 2 3 4

I am working on a product page created with WordPress that fetches products and displays them. However, I want to restrict the number of products visible at once. Code for generating with WordPress/PHP: $pages = get_pages(array('parent' => $ ...

jQuery validation for custom start and end dates

I am seeking to implement custom validation for two date inputs using @Html.EditorFor in a specific view. The goal is to ensure that the start date is before or equal to the end date. Below is the code I have tried: <div class="form-group"> @Htm ...

Can the bottom border on an input textfield be removed specifically under the new character?

This is the new visual design I received: https://i.stack.imgur.com/kiQGe.png The label CLG is represented as a label, with the line being an input type=tel. Disregard the purple overlay... The designer has requested that I remove the border when a user ...

Loading remote content on a server for my Firefox OS application - On the Web and FxOS device

I haven't come across this issue in any forum, so I decided to reach out here. I'm encountering a problem with my FirefoxOS app on my FirefoxOS device (Geeksphone Developer Preview) when trying to retrieve remote content from the server. I am m ...

Safari does not display disabled input fields correctly

I have designed a simple angular-material form with various inputs that are organized using angular flex-layout. The form displays correctly in all browsers except for Safari on iOS devices. The problem in Safari arises when loading a form that contains d ...

How to eliminate a hyperlink from an HTML element with the help of JQuery

Recently, I was assigned to revamp a website for the company I work for. However, upon closer inspection, I realized that the website is quite messy and relies heavily on templates, resulting in certain elements being auto-generated as active links. The i ...

Trouble with HTTPS request in Android fragment

My app crashes and returns to the main activity whenever I try to use the search function with the Kitsu API in my fragment. I have observed through Logcat that no data is being fetched, but I am unable to determine what is causing the crash.The LogCat r ...

Angular does not recognize the function element.sortable

I'm attempting to utilize ui.sortable in order to create a sortable list. Despite following the instructions provided at https://github.com/angular-ui/ui-sortable, I am still encountering an issue and receiving the following error message: TypeError: ...

Utilizing jQuery grep() to sort through a JSON array

Despite my attempts to find a suitable example on this platform, I am still struggling to adapt them to my specific needs. Essentially, all I require is to filter some JSON results using the grep() function. Here is the JSON data that I am working with: ...

d3.json is unable to parse a value of 'Infinity

My goal is to retrieve data from an SQLite database and convert it into JSON format for use with d3.js in order to create a graph. I have successfully obtained this data in JSON format using the following URL: http://localhost:8085/SQLQuery/?date1=2019-03 ...

Align content to the bottom using Bootstrap 4

Looking for help with aligning content to the middle and bottom on a full-page bootstrap layout? The first page has a background image in the first div, and a darker layer on top in the second div. <div class="h-100 w-100"> <div class="h-100 w-10 ...

My custom class is being ignored by Tailwind CSS within breakpoints

I'm attempting to incorporate some animation on the height property within the md breakpoint, but for some reason Tailwind CSS isn't applying my class. <div className={`h-12 bg-blue flex w-full text-white fixed mt-1 md:bg-white ${scrolling ? ...