tags:

views:

54

answers:

3

I have a link appended to a div element. And on clicking the link, I want a function to be executed.In order to check if the function is called, when I click the link, i had an alert box in that function. But no alert box is appearing if I click the link?

This is the link added to the div element 'fb_contentarea_col2top'.

$("<p class='title2'>Recent Entries | <a id='actions' href='#'>Actions</a> </p>").appendTo("#fb_contentarea_col2top");

When I click this link, I want this function to be called,

$('#actions').click(function (){
 alert("HI");

});

But the alert does not come. What is the mistake I am doing?

+5  A: 

You'll want to change "click" to live:

$("#actions").live("click", function() {
  alert("hi");
});

This will bind the actions to any #actions that presently exists, or will exist in the future. In your case, you're adding it in later.

Jonathan Sampson
...or, bind the click event after you create the element.
Kieron
Thank you... :)
Angeline Aarthi
A: 

Have you got the script inside a document ready block. Else use .live outside the ready block.

$(function(){

  $('#actions').click(function (){
        alert("HI");

  });

});
redsquare
A: 

Try this:

$("#actions").bind('click', function() {
    alert("HI");
});
Craig Martek
what is the difference with what she has already?
redsquare
.live('click') works as Jonathan has suggested..
Angeline Aarthi
.bind and .live are slightly different: live binds to all future matches (which shouldn't be a problem, since id's should be unique). I'm just more used to using .bind, which is why I suggested it.
Craig Martek