With Javascript we have to learn to think in functions. You got it partly right with the way you attach your behavior to the button click.
But we need a named function to wrap your code to get it behave as expected.
This is how your code needs to be changed into order to work correctly: