javascript - why does my 'click' addEventListener getting called on pageload -
i have button id #login , javascript file line:
document.getelementbyid('login').addeventlistener('click', 'loginpressed()')
as test, made function:
function loginpressed(){ console.log('was login pressed already??') }
and function getting called every time page loads. how stop happening?
note, i've tried callback not in quotes, , not function:
document.getelementbyid('login').addeventlistener('click', loginpressed()) document.getelementbyid('login').addeventlistener('click', loginpressed) document.getelementbyid('login').addeventlistener('click', 'loginpressed')
because invoking it, rather referencing it.
this:
document.getelementbyid('login').addeventlistener('click', 'loginpressed()');
should this:
document.getelementbyid('login').addeventlistener('click', loginpressed);
there should not parenthesis after loginpressed
because want refer the function can known function call later. parenthesis there, invoking right away.
there should not quotes around loginpressed actual name of function. quotes there, javascript runtime won't recognize function properly.
here's code, correctly written , working (notice how console message not appear until click button):
document.getelementbyid('login').addeventlistener('click', loginpressed) function loginpressed(){ console.log('was login pressed already??') }
<button id="login">click me</button>
Comments
Post a Comment