1

I want Joomla to add a class like "loggedIn" to body classes, when a user is logged in the page, in order to use this class and make specific css changes for logged in and non-logged in users.

I am using this jQuery to add a class to body but of course it missing the code to recognize if someone is logged in.

jQuery(function ($) {
$( 'body' ).addClass( 'my-style' );
});

I also use the code below as php:

<?php
$user = JFactory::getUser();
$status = $user->guest;

if($status == 1){
//do user logged out stuff

}
else
{
//do user logged in stuff

}
?>

So in fact I want a combination of the above as jQuery

0
1

You can use addScriptDeclaration to add some custom Javascript to the buffer, like so:

<?php

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

Also note that I've used vanilla JS, as you don't need jQuery to add a class.

13
  • I added the code inside the Regular Labs Sourcerer module, but I see this error on frontend: syntax error, unexpected 'use' (T_USE)
    – geoplous
    Nov 29 '21 at 12:15
  • @geoplous - I've updated the code, which should now work with Sourcerer
    – Lodder
    Nov 29 '21 at 12:36
  • error fixed but I can not see the new class after login...
    – geoplous
    Nov 29 '21 at 17:17
  • Do you see any errors on your browser console?
    – Lodder
    Nov 30 '21 at 5:07
  • No I do not see any errors
    – geoplous
    Nov 30 '21 at 5:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.