Search code examples
javascriptif-statementwindowonload

window.onload if error - statement expected


window.onload(
    if(localStorage.getItem('name') !== null) {
        $('#greet').html('Hello ' + localStorage.getItem('name'))
    };
);

Why do i get a statement expected error on the if here? Can't i put if-s in window.onload?


Solution

  • Your code is wrong this is the write one. Because You should assign function to window.onload. Read the documentation : https://developer.mozilla.org/en/docs/Web/API/GlobalEventHandlers/onload

    window.onload = function() {
      if (localStorage.getItem('name') !== null) {
        $('#greet').html('Hello ' + localStorage.getItem('name'));
      }
    };