Archive for category Mobile

Why a Cordova function executes at page load

I have recently been experimenting with the Cordova libraries to create cross-platform mobile applications using Visual Studio 2015. If you are interested in learning about Cordova, I found this tutorial to be very helpful.

Being new, I just wanted to go off-script and create a button to say “Hi”. So I had a basic HTML page with a reference to my JavaScript file (I have ripped out all the other code to make the example more readable):

<!DOCTYPE html>
    <button id="find" data-role="button">Find</button>

In my JavaScript file, find.js, I had a simple method to display the results of a JS alert:

$(document).ready(function () {
    $('#find').bind("click", alert('Hi'));

My expectation was that this would only execute when I click the button, which my years of development experience led me to believe. But things were different here, and I was getting the “Hi” message when my application loads.

Luckily, I found a nice Stack Overflow post explaining the problem, and the solution. To fix this behavior, I had to stick the alert call into a method and modify the bind statement:

$(document).ready(function () {
    $('#find').bind("click", alerty);
function alerty() {

Notice that when I reference “alerty” in the bind statement, I don’t include any parentheses.


Leave a comment