3

I did everything I could to make it happen, but without success.

The problem is that I create an element on runtime then bind a function to the element like the following code:

$(document).ready(function() {

  $('.rem').click(function() {
    $("body").append('<a id="runtime" href="javascript:void(0);">runtime</a>');
  });

  $('#runtime').bind('click', func_name());

});

//End of doc
function func_name() {
  alert('I got it!');
}

In the HTML code I have a label like below:

<div id="body">
  <label class="rem">click me</label>
</div>

My second attempt

$(document).ready(function() {

  $('.rem').click(function() {
    $("body").append('<a id="runtime" href="javascript:void(0);">runtime</a>');
  });

  $('#runtime').bind('click',function() {
    alert($(this).text());
  });

});
//End of doc

HTML code:

<div id="body">
  <label class="rem">click me</label>
</div>
davegson
  • 7,882
  • 4
  • 49
  • 69
Alireza
  • 5,659
  • 11
  • 52
  • 118

3 Answers3

6

Change

$('#runtime').bind('click',func_name());

to

$('#runtime').live('click',func_name); 

or (as of jQuery 1.7):

$('#runtime').on('click',func_name); 

Two things to note:

  1. I changed func_name() to func_name. You don't want to call the function when you bind the handler - you just want to reference it.
  2. Calling bind won't do you any good, because #runtime doesn't exist until after you've clicked .rem. That's why you need either live or on (depending upon your jQuery version).

And just for good measure: here's a good reference on why you should be using jQuery.on anyway.

Community
  • 1
  • 1
Chris Tonkinson
  • 13,033
  • 13
  • 55
  • 88
3

You don't want to run the function at the point in the code, so remove the ():

$('#runtime').bind('click', func_name);

If you're using jQuery 1.7+, though, you should either use .on():

$('#runtime').on('click', func_name);

or use a .click() handler directly:

$('#runtime').click(func_name);
kevinji
  • 10,259
  • 4
  • 36
  • 56
  • I use jQuery 1.7.1.min.js but .on() method did not work (I removed () from function) – Alireza Mar 08 '12 at 05:40
  • I don't think .click() work well, because my element has been added on runtime, I need to bind event to it! – Alireza Mar 08 '12 at 05:41
0

try this

$(document).ready(function(){

    $('.rem').click(function(){
        $('<a id="runtime" href="javascript:void(0);">runtime</a>').bind('click',func_name).appendTo("body");
    });
});//End of doc
function func_name(){
    alert('I got it!');
}

Since you are binding the object before it has been created, you are not getting the desired result.

Tejasva Dhyani
  • 1,332
  • 1
  • 10
  • 19