0

I want to show the top menu to users depending on their login status. The difference is like below:

  • Zaloguj - non logged in users

  • Wyloguj - logged-in users

I need the code to work when a page is loading but it is not. What is wrong with the code below?

<div>
  <div id="non_loggedIn" style="display:block">
    Baza wiedzy - 1
  </div>

  <div id="loggedIn" style="display:block">
    Baza wiedzy - 2
  </div>

  <div id="login-status">
    Zaloguj
  </div>
</div>

and JS code:

window.onload = function() {
  var loginStatus = document.getElementById('login-status').innerText;
  var loggedIn = document.getElementById('loggedIn').style.display;
  var non_loggedIn = document.getElementById('non_loggedIn').style.display;


  console.log('loggedIn: ' + loggedIn);
  console.log('non-loggedIn: ' + non_loggedIn);
  console.log('loginStatus: ' + loginStatus);

  if (loginStatus == 'Zaloguj') {
    loggedIn = 'block'
    non_loggedIn = 'none'

  } else {
    loggedIn = 'none'
    non_loggedIn = 'block'
  }
  
   console.log('loggedIn: ' + loggedIn);
  console.log('non-loggedIn: ' + non_loggedIn);
  console.log('loginStatus: ' + loginStatus);
}

Link to jsfiddle: https://jsfiddle.net/xmves0qb/

2
  • 2
    You're changing a variable, not the style itself. Try setting document.getElementById('non_loggedIn').style.display = 'none' Commented Nov 8, 2022 at 10:33
  • It's looks like your code is working, see in the console the output Commented Nov 8, 2022 at 10:38

1 Answer 1

1

You're currently just changing the values stored in your variables. If you store the actual HTML Element in your variable you can change the style in your if.

window.onload = function() {
  const loginStatus = document.getElementById('login-status').innerText;
  const loggedIn = document.getElementById('loggedIn'); // removed style.display here
  const non_loggedIn = document.getElementById('non_loggedIn'); // removed style.display here

  if (loginStatus == 'Zaloguj') {
    loggedIn.style.display = 'block' // added style.display here
    non_loggedIn.style.display = 'none' // added style.display here

  } else {
    loggedIn.style.display = 'none' // added style.display here
    non_loggedIn.style.display = 'block' // added style.display here
  }
}
<div>
  <div id="non_loggedIn" style="display:block">
    Baza wiedzy - 1
  </div>

  <div id="loggedIn" style="display:block">
    Baza wiedzy - 2
  </div>

  <div id="login-status">
    Zaloguj
  </div>
</div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.