Mike Eng
Mike Eng

Reputation: 1681

jQuery function called in a .bind click handler is running on document ready

I defined a simple function and attached a "click" handler to a link using .bind().

The function is not running on click - rather, it is running on document ready. Not sure why this is happening.

I am using jQuery 1.3.2.

HTML

<a href="#">click me</a>

jQuery

$(document).ready(function(){
  leftTurn = function($message){
    alert ($message);        
  };

  $('a').bind('click', leftTurn('hello'));
});

The code is also here in a JSFiddle

Upvotes: 3

Views: 2395

Answers (2)

kobe
kobe

Reputation: 15835

You're calling the function when you include () at the end. The .bind() function expects a reference to the function itself, not the called result.

leftTurn = function(){
        alert ('hello');        
    };

$(document).ready(function(){
    $('a').bind('click', leftTurn);
});

Upvotes: 5

jyoseph
jyoseph

Reputation: 5455

I think you may want to use the callback/handler of bind:

$('a').bind('click', function(){
    leftTurn();    
});

Demo

From the docs:

 .bind( eventType, [ eventData ], handler(eventObject) )

Upvotes: 3

Related Questions