Tuesday 21 May 2013

OnLoad Event in PageLayouts in SharePoint 2010

Today I came across a different problem. I wanted to add JavaScript or jQuery into SharePoint Page Layout which it will run when page loaded.

I'v tried jQuery $(document).ready(function() { }); and JavaScript window.onload, but nothing seemed to work.

Finally I found out that the MS SharePoint team has given the developers a way to do this easily, using a special array called _spBodyOnLoadFunctionNames. The only thing you have to do is push your function's name to this array and it will get called in the OnLoad event of the window.

Below is the function which depicts how the _spBodyOnLoadFunctionNames function is used inside Javascript.


<script type="text/javascript">
_spBodyOnLoadFunctionNames.push("HideLink");
function HideLink(){
document.getElementById('DocName').style.visibility = "hidden";
}
</script>

The above function hides the tag with id as 'DocName' when a page loads, which in turn comes from the Page Layouts.

This solution should also work for visual webparts that needs to call a javascript function OnLoad.(Not tested though..).

Happy SharePointing.... :)