Ja5onHoffman
Ja5onHoffman

Reputation: 672

Why is this click event automatically triggered in jQuery?

I'm creating a simple app using JS/jQuery as a learning exercise and am running into a problem I've encountered before and can't seem to solve. Why, in the following code, is the second click event triggered automatically rather than when I click $('.tweet li a.username')?

$(function(){
   setInterval(update, 3000);
    $('.showMore').on('click', function() {
      moreIndex += 5;
      update();
    })
    $('.tweet li a.username').on('click', alert('hey!'));
  });

alert('hey!') is filler for a function I'm still working out. How should this be organized so that the click event triggers when the link is clicked rather than when the page loads? The $('.showMore') event works properly, even if I change the order.

Upvotes: 0

Views: 140

Answers (2)

Arun P Johny
Arun P Johny

Reputation: 388316

it is because you are invoking the alert function there instead of passing the callback function reference.

In your case you are invoking the alert() function and pass the value returned by the alert as the click event handler.

$('.tweet li a.username').on('click', function(){
    alert('hey!')
});

Upvotes: 3

Blazemonger
Blazemonger

Reputation: 92923

You need to wrap the alert in a callback function, just like the first example:

$('.tweet li a.username').on('click', function() { alert('hey!') });

The .on method is expecting a JavaScript object in that position, a function in particular, which it can execute later. What is happening in your original code is that the JavaScript engine is looking for a function, but sees some other code there instead -- so it executes the code there (activating the alert) in hopes that a useful object will be returned. (When nothing is returned, the JavaScript engine instead assumes that you want null to be executed on a click event, and happily does so.)

Upvotes: 1

Related Questions