correctly put if statement inside event handler