Add a class to body tag when a user is logged in

Sometimes we want to add a class in body when a user is logged in in order to make specific css changes for these users. In order to do that follow these steps:

  1. Use the Regular Labs Sourcerer or any other Joomla module that can add php on a module position.
  2. Copy paste the code below to “code” :
<?php

if (\Joomla\CMS\Factory::getUser()->guest === 0)
{
    \Joomla\CMS\Factory::getDocument()->addScriptDeclaration("
        document.addEventListener('DOMContentLoaded', () => {
            document.body.classList.add('loggedIn')
        });
    ");
}
?>

3. Do not forget to go to the Options tab in the module and enable the Prepare Content field.

The next time you log in you will see the class: “loggedIn” inside your body classes.


A working scenario for this can be a custom login module with a code like this:
(class=”item-1888″ is a popup from Engage Box component that shows the Joomla login module)

<div class="hide-when-loggedIn">
	<div class="top-signin"><span class="item-233"><i class="fas fa-user"></i> Signin</span></div>
</div>
<div class="hide-when-loggedOut">
	<div class="top-signin"><span class="item-233"><i class="fas fa-user-slash"></i> Sign Out</span></div>
</div>
.hide-when-loggedOut {
	display: none;
}
.hide-when-loggedIn {
	display: block;
}
.loggedIn {
	.hide-when-loggedOut {
		display: block;
	}
	.hide-when-loggedIn {
		display: none;
	}
}


Scroll to Top