I'm attempting to use a piece of JS that I located here to add some CCS classes to the body tag of my SP site based on the user's groups. The following script works perfectly well when looking at a particular group's membership page. (sites/[mysite]/_layouts/15/people.aspx?MembershipGroupId=XXX
)
But, the script throws a Cannot read property 'get_current' of undefined
error anywhere else.
The relevant code is below:
jQuery(document).ready(function($){
// generic function to grab user groups from collection. Used to append class names to body tag for CSS styling.
// Inspired by: https://sharepoint.stackexchange.com/questions/89241/user-group-or-role-based-on-logged-in-user-at-client-side-script
function GetGroupCollectionFromCurrentUser(OnSuccess,OnError) {
var context = SP.ClientContext.get_current();
var web = context.get_web();
var currentUser = web.get_currentUser();
var groups = currentUser.get_groups();
context.load(groups);
context.executeQueryAsync(function(){
OnSuccess(groups)
},
OnError);
}
GetGroupCollectionFromCurrentUser(function(groups){
var e = groups.getEnumerator();
while (e.moveNext()) {
var group = e.get_current();
var groupClass = (group.get_title()).replace(/\s+/g, '');
$("body").addClass("group-" + groupClass);
}
},
function(sender,args){
console.log('An error occured:' + args.get_message());
}
);
.... more code, all working.
});
When not producing an error, the body class of the page looks like:
<body ... class="group-groupName group-SecondGroupName" ... >
My question: Is there a better way to call these functions so that I can acheive the desired result? Is there better way to accomplish the same thing?