Why is the jQuery on(“click”, “button”, …) running before the button is clicked?

I’m just learning jquery, and I’m running into behavior I don’t understand. I have:

html:

<div id="tour" data-location="london">
  <button>Get Photos</button>
  <ul class="photos"></ul>
</div>

and jquery:

var tour = {
  init: function () {
    $("#tour").on("click", "button", alert("clicked"));
  }
};
$(document).ready(function () {
  alert("hello");
  tour.init();
});

The “hello” alert is appearing after the dom is loaded, as I would expect. However the “clicked” alert is firing as well, and does not subsequently fire when the button is pressed.

http://jsfiddle.net/abalter/295sgf5c/2/


solution

If you want it to be executed when clicking on the button, you would need to wrap it in a function:

Updated Example

var tour = {
  init: function () {
    $("#tour").on("click", "button", function () {
        alert("clicked")
    });
  }
};