Reputation: 2797
I know how to check if the user is logged in through PHP, but I need to do some styling when an event occurs, and I created a separate JavaScript file for this. Is this a Drupal variable or something which I can reference too?
Upvotes: 9
Views: 10915
Reputation: 260
For Drupal 8 if you use Drupal.behaviors, you can access the user UID in settings:
(function($, Drupal, viewport, settings) {
"use strict";
Drupal.behaviors.ifCE = { //the name of our behavior
attach: function (context, settings) {
var userUID = settings.user.uid;
//your code...
}
})(jQuery, Drupal, ResponsiveBootstrapToolkit, drupalSettings);
So if the userUID === 0
then your user is not logged in.
Upvotes: 6
Reputation: 119
I checked if the element #toolbar-administration exists since Drupal 10.
let isLoggedIn = jQuery("#toolbar-administration").length === 1;
Upvotes: 0
Reputation: 27053
Create a new custom module with hook_init implementation.
function [YOUR_MODULE]_init()
{
global $user;
drupal_add_js(array('user_js_uid' => $user->uid), 'setting');
}
Then in your javascript code, check for the value of the variable defined in the module user_js_uid
.
if(Drupal.settings.user_js_uid == 0)
{
// execute code for non logged in users
}
else
{
// execute code for logged in users
}
Upvotes: 16
Reputation: 195
The "not-logged-in" class doesn't seem to exist in vanilla Drupal 8. But there's "user-logged-in" instead. Here's one line of CSS I'm using to hide the custom "Register" menu item if a user is logged in:
body.user-logged-in a[href="/user/register"] {display: none; }
Upvotes: 2
Reputation: 421
If you are waiting for the DOM to be ready and use standard generated Drupal CSS classes, you could do something like (with jQuery):
if( $( "body.not-logged-in" ).length )
{
// user is not logged in
}
Upvotes: 15