Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 508
Sridhar Venkat Avatar asked Nov 29 '16 07:11

Sridhar Venkat


1 Answers

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

Change this

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

to this

document.getElementById("showLocalStorage").addEventListener("click", showLocalStorage);
like image 157
Afsar Avatar answered Sep 29 '22 21:09

Afsar