Sometimes we need to run code which will be executed when Sharepoint ribbon is opened. In many cases ribbon is closed by default and you can’t access its elements in regular document.ready handler because ribbon elements are not created in the DOM yet. In this case you need to subscribe somehow on ribbon.open even and access elements there. This is how it can be done:
ExecuteOrDelayUntilScriptLoaded(function() { SP.Ribbon.PageManager.get_instance().add_ribbonInited(function(){ console.log("Ribbon is opened"); }); }, "sp.ribbon.js");
Interesting that even inside this handler you can’t access elements via jQuery selector because it doesn’t find these dynamically added elements. So e.g. the following code which tries to access New document tab in doclib will return 0:
$("#Ribbon.Documents.New").length
In order to access these dynamically added ribbon elements we need to use pure javascript call document.getElementById. Here is the full code:
ExecuteOrDelayUntilScriptLoaded(function() { SP.Ribbon.PageManager.get_instance().add_ribbonInited(function(){ var el = document.getElementById("Ribbon.Documents.New"); if (el) { console.log("New document tab is found"); } }); }, "sp.ribbon.js");
Using this approach you will be able to access and manipulate ribbon elements via javascript.
No comments:
Post a Comment