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

1
  • +1 for well formed question and jsfiddle link. @gov's answer taught me something too! Commented Dec 17, 2010 at 17:32

2 Answers 2

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);
});
Sign up to request clarification or add additional context in comments.

2 Comments

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
I would probably write it as jyoseph did, but alternatively you can pass data into the handler like so: api.jquery.com/on/#passing-data
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) )

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.