Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

I'm trying on my site's homepage to close a web part programmatically using Javascript. The code fires, but the web part doesn't close. How can I close the web part programmatically?

var clientContext = new SP.ClientContext('/');
var oFile = clientContext.get_web().getFileByServerRelativeUrl('/default.aspx');
var limitedWebPartManager = oFile.getLimitedWebPartManager(SP.WebParts.PersonalizationScope.user);
var webParts = limitedWebPartManager.get_webParts();
var webPartDefinition = webParts.getById(webPartGuid);
webPartDefinition.closeWebPart(); // webPartDefinition.deleteWebPart();
clientContext.executeQueryAsync(Function.createDelegate(this, this.onRemoveSucceeded), Function.createDelegate(this, this.onRemoveFailed));

Known:

  • The same code works for deleting the web part (substitute deleteWebPart() for closeWebPart())
  • webPartGuid is known before the code fires (again: delete succeeds w/o problem)
  • onRemoveSucceeded is getting called when I'm trying to close, but the web part is still open
share|improve this question
add comment

1 Answer 1

up vote 0 down vote accepted

Where webPartDiv is the jQuery object of the web part's <div> having the 'WebPartID' attribute:

function CloseWebPart(webPartDiv) {
    var webPartHtmlDomObject = GetHtmlDomObjectFromJqueryObject(webPartDiv);
    MSOLayout_RemoveWebPart(webPartHtmlDomObject);
}

function GetHtmlDomObjectFromJqueryObject(jQueryObject) {
    var result = jQueryObject.get(0);
    return result;
}

MSOLayout_RemoveWebPart lives in the SharePoint JS files.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.