Home > OS >  Hide div on page load with JS. Problem with code
Hide div on page load with JS. Problem with code

Time:11-08

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/

CodePudding user response:

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>

  • Related