On my page I have a header such as
<header >
<-- stuff goes here -->
</header>
When my page loads, I would like to change the class from headerMain to headerManager, headerSuper, and so on based on the users role. How can I change the class to be used when the page is loaded?
I tried:
(function ($) {
if(Role == "Manager")
{
document.getElementsByClassName("headerMain").toggleClass("headerManager");
}
})
Is there a better way to do this?
CodePudding user response:
If you are using jQuery, you can perform the following.
jQuery(function($){
$(".headerMain").removeClass("headerMain").addClass("header" Role);
});
If Role
is one of the following values:
- Main
- Manager
- Super
Then the class will be updated to match the Role.
Personally, I would separate the Class name. Start with a base HTML like:
<header >
<-- stuff goes here -->
</header>
In this way you can simply add the Role when the page loads.
$("header.header").addClass(Role);
Your Class is then header Main
or header Super
from the get go. Adjust your CSS to match: .header.Main
and .header.Super
respectively.
CodePudding user response:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<header >
<-- stuff goes here -->
</header>
<script>
$( function() {
var Role = 'Manager';
$(".dynamicClass").removeClass('headerMain headerManager headerSuper');
if(Role == "Manager"){
$(".dynamicClass").addClass('headerManager');
}else if(Role == "Super"){
$(".dynamicClass").addClass('headerSuper');
}else{
$(".dynamicClass").addClass('headerMain');
}
})
</script>
</html>