Sridhar Venkat Sridhar Venkat - 3 days ago 7
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.

<body>
<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>
</div>
<button id = "setLocalStorage">SET LOCAL STORAGE</button>
<br/>
<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>
</div>
<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>
</body>


Javascript

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


Please point me where i did mistake. Thanks.

zan zan
Answer

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);
Comments