abalter
abalter

Reputation: 10393

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/

Upvotes: 0

Views: 456

Answers (2)

Josh Crozier
Josh Crozier

Reputation: 241188

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")
        });
    }
};

Upvotes: 7

Ted
Ted

Reputation: 14927

See this fiddle.

Your callback needs to be a function, like this:

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

Upvotes: 5

Related Questions