3

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

Mike Eng
  • 1,593
  • 4
  • 34
  • 53

2 Answers2

5

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);
});
Soviut
  • 88,194
  • 49
  • 192
  • 260
kobe
  • 15,671
  • 15
  • 64
  • 91
  • Nice. Works in a simple function with no arguments, but how do you pass an argument to the function? I edited the code in the question and the jsfiddle – Mike Eng Dec 17 '10 at 17:38
  • 1
    I would probably write it as jyoseph did, but alternatively you can pass data into the handler like so: http://api.jquery.com/on/#passing-data – Matthias Jan 15 '15 at 14:17
3

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) )
jyoseph
  • 5,435
  • 9
  • 45
  • 64
  • 2
    Yep -- I made this mistake a lot early on working with jQuery. Wrapping a function call inside a function is still a little odd to me. – jwheron Dec 17 '10 at 17:29