Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

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

like image 634
Mike Eng Avatar asked May 03 '26 08:05

Mike Eng


2 Answers

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);
});
like image 129
kobe Avatar answered May 07 '26 10:05

kobe


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) )
like image 42
jyoseph Avatar answered May 07 '26 11:05

jyoseph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!