Johnny Appal Johnny Appal - 2 months ago 7
MySQL Question

jQuery - click() not working when attached to anchor created in PHP

I have this PHP code which outputs HTML anchor elements on a page:

if(!$isOnOwnPage)
echo '<a id="message-button" class="button">Message</a>';
if($isOnOwnPage)
echo '<a id="add-img-button" class="button">Add Image';
else if(!$isFollowing)
echo '<a id="follow-button" class="button">Follow';
else
echo '<a id="follow-button" class="button">Unfollow';
echo "</a>";


When I load the web page, I get this, as expected:

...
<a id="message-button" class="button">Message</a><a id="follow-button" class="button">Unfollow</a>
...


But when I try to attach a click() function to it, the clicking doesn't work. This is the jQuery code. (It's weird because all of my other JS on the page works flawlessly."

$('.button').click(function() { alert("HEY"); }); // It doesn't work grabbing by #follow-button or #message-button either.


What did I do wrong here? I've spent an hour looking at these snippets of code to no avail.

Answer

Try this:

$('.button').live('click',function() { alert("HEY"); });

Put it in your $(document).ready function.

Comments