Only show element to logged in members

Hello,

I would like to hide an element by default, and only show it to members that are logged in. I have searched and searched for codes but cannot find any. I’m not super advanced yet, can anyone help me out with an example?

Thanks so much!

Regards, Stefan

Seems like it should be easy enough. Set the element to be hidden by default, then do something like

import { authentication } from 'wix-members';

$w.onReady(function () {

const isLoggedIn = authentication.loggedIn();

if (isLoggedIn) {
  $w("#nameOfHiddenElement".show()
}
})

You can check out loggedIn here:

Thanks so much!

@simen
Hi,
Thank you for your answer, I try this code, but don’t work for me.
Because the element is in header, is a button.
Do you have any idea how can I solve that?
Since now, I thank you so much.
Cris

Hi!

You should put the code @simen posted into masterPage.js as that’s where all code related to global sections (header, footer, etc) and their elements should be put.

More info here: Where Do I Put My Code? | Velo

@luka_atanackov Awesome! Your tip worked exactly as I wanted.

Thank you so much!

But I use this other code:

import { authentication } from ‘wix-members’; // Importa a API de autenticação de membros do Wix

$w.onReady(function () {

// Verifica se o visitante está logado

if (authentication.loggedIn()) {

// Se estiver logado, mostra o elemento. Substitua ‘#nomeDoSeuElemento’ pelo ID real do seu elemento.

$w(‘#nomeDoSeuElemento’).show();

} **else** {

// Se não estiver logado, mantém o elemento oculto (ou pode escondê-lo explicitamente, se preferir)

$w(‘#nomeDoSeuElemento’).hide();

}

});

// Opcional: Adicione um ouvinte de evento para quando o usuário fizer login ou logout dinamicamente na mesma página

authentication.onLogin(() => {

$w(‘#nomeDoSeuElemento’).show();

});

authentication.onLogout(() => {

$w(‘#nomeDoSeuElemento’).hide();