Sridhar Venkat Sridhar Venkat - 6 months ago 59
Javascript Question

Cordova: onclick event is calling before button click

I am new to cordova and javascript. I am just trying to print some message and want to show alert when i click the button. But it is happening once the app is loaded.

This is my code.

<div class="app">
<h1>Apache Cordova</h1>
<div id="deviceready" class="blink">
<p class="event listening">Connecting to Device</p>
<p class="event received">Device is Ready</p>
<button id = "setLocalStorage">SET LOCAL STORAGE</button>
<button id = "showLocalStorage">SHOW LOCAL STORAGE</button><br/>
<button id = "removeProjectFromLocalStorage">REMOVE PROJECT</button><br/>
<button id = "getLocalStorageByKey">GET BY KEY</button>
<p id="demo"></p>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript" src="js/myscript.js"></script>


document.getElementById("showLocalStorage").addEventListener("click", showLocalStorage());
function showLocalStorage() {
document.getElementById("demo").innerHTML = "value is empty";
alert("am i amazing!!")

Please point me where i did mistake. Thanks.

zan zan

Do not execute the function , just bind it to addEeventListener and execute it when clicked.

Change this

document.getElementById("showLocalStorage").addEventListener("click", showLocalStorage());

to this

document.getElementById("showLocalStorage").addEventListener("click", showLocalStorage);