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

Choose the correct checkbox among several options

On my webpage, I am facing an issue with checkboxes. No matter which checkbox I click on, only the first one is getting checked. I can't figure out what the problem is. Initially, the checkboxes weren't showing as checked, but now only the first ...

Using NodeJS and EJS to Display MySQL Query Results

I am currently working on a project where I need to display data retrieved from a MySQL query in an HTML table. However, when I attempt to do so, I encounter the following output: [object Object],[object Object],[object Object],[object Object],[object Obj ...

Refine the Crossfilter dimension according to the specified date range

What is the proper way to filter a date range using Crossfilter? The code above does not seem to yield any results, but I am certain that there are records within that specified time period. Var myDimension = CrossFilterObj.dimension(function(d) { retur ...

Error during compilation due to a missing parenthesis in the loop structure

I've been experimenting with creating a carousel using just html and css, without any Javascript. I've been exploring resources on the web and following tutorials to achieve this goal. However, I've encountered an issue. I created a mixin l ...

Determine the data type of an object's key

I have a XInterface defined as: export interface XInterface { foo: (() => Foo[]) | Foo[], bar: string, baz: number } When declaring an object using this interface, I want the type of foo to be Foo[], like so: const myObj: XInterface = { ...

Retrieve information from an HTML form

Currently, I have a piece of Javascript that fetches the HTML for a form from the server using an XMLHttpRequest and then displays the form on the page. I am looking for a solution to extract the data that would be sent via POST if the form were submitted ...

Load an external URL and load a file from the local directory using Electron

For an upcoming art exhibition, I have a video installation that consists of large videos (several GBs) and an online hosted web application. To conserve bandwidth during the exhibition, I am considering packaging the videos into an electron app. This way ...

Avoiding an endless spiral on a setter in JavaScript/TypeScript

Implementing TypeScript, I've been working on setting up a concept called a "trigger" : an object that includes both a checker function (which returns a Boolean) and a behavior function capable of performing various tasks. My aim is to execute the che ...

Using Google API to retrieve Gmail data in Java by accessing it with an id_token obtained from JavaScript

Utilizing the gapi in JavaScript via OAuth2 to retrieve googleUser.getAuthResponse().id_token, which I then send to my server. My goal is to utilize the Java API to interact with the Gmail API and list messages on the account. However, I'm encounterin ...

Encountering difficulty with the Cheerio find method during web scraping

I have been working with the code below: var request = require('request'); var cheerio = require('cheerio'); var url = "http://www.mbl.is/feeds/fp/"; request(url, function(err, resp, body) { if (err) throw err; $ = chee ...

"Any tips on maintaining the blue color of my dropdown link when it is selected as active

I'm struggling to keep the bootstrap accordion dropdown link blue when it's active. I've tried different methods but none seem to work. What am I missing? Here's my code: <div class="visible-sm visible-xs" id="accordion" role="t ...

Trouble with Click event not working in Electron and mouse cursor not changing when hovering over an HTML button?

I'm in the midst of a project that involves using the electron framework. Within my project, I have an HTML file, a CSS file, and a Javascript file. The issue at hand is that when I hover over a button, the expected hand pointer icon fails to appear d ...

The inclusion of HttpClient is causing issues with the functionality of my component

Currently, I am facing an issue with my Angular service called ConnexionService. The problem arises when I try to incorporate CSV files into this service using HttpClient. Strangely, the component associated with this service fails to display once HttpClie ...

Enable scrolling for a div positioned beneath another div

I am working with an iPad frame and trying to implement a feature where a larger image scrolls behind it as the user scrolls down the page. Although my CSS is more complex than the example provided in this link, I am struggling to get even that basic funct ...

How can Express JS be configured to make URL calls from a local environment?

I encountered an issue with my code (Weather App using OpenWeatherMap Api) when I attempted to move my apiKey and apiUrl to the .env file. An error appeared in the terminal, but it's unclear why it occurred. Below is my code: const express = require( ...

Express and Node.js working together

Recently, I've been encountering an issue with my POST function. Whenever I click on the log in button, a message pops up saying: Cannot POST /login I'm at a loss here and would greatly appreciate any help you can provide \(^-^\) B ...

Is the NodeJS rmdir function experiencing issues specific to LINUX?

Currently, I have a NodeJS script section that runs on my Windows 10 machine with the latest Node version and another version on my CentOS8 Linux webserver. The code executes as expected on Windows but throws an error when running on Linux at this specific ...

What causes the "500: Unknown web method" error when JavaScript tries to call a Page WebMethod?

I am encountering an issue with a method in CreateTicket.aspx.cs: [WebMethod()] public static string Categories() { var business = new CategoryBusiness(); var categories = business.ListRootCategories(); return categories.Json(); } Additiona ...

Using a timer to make Ajax calls twice on a single webpage

Can multiple ajax calls be made simultaneously on the same page to different receiving div tags? I am struggling to find a solution to this issue. I have a total of 3 pages: a home page, and two PHP pages named status and alert which echo the results. Wi ...

During the present module, retrieve the runtime list of all modules that are directly imported (Javascript/Typescript)

Imagine you have a set of modules imported in the current module: import {A1, A2, A3} from "./ModuleA"; import {B1, B2, B3} from "./ModuleB"; import {C1, C2, C3} from "./ModuleC"; function retrieveListOfImportedModules() { // ...