jQuery Class selector not working

dan picture dan · Jul 6, 2011 · Viewed 34.3k times · Source

I'm struggling to make an alert come up when an anchor tag with a specific class is clicked inside of a div.

My html section in question looks like this...

<div id="foo">
  <a class='bar' href='#'>Next</a>
</div>

The jQuery section is as follows..

$('.bar').click(function()
{
  alert("CLICKED");
});

My problem is that I cannot get this alert to come up, I think that I'm properly selecting the class "next", but it won't pick it up for some reason. I've also tried almost everything on this page but nothing is working. If I don't try to specify the anchor tag i.e. $('#foo').click(function()... then it works, but there will be multiple anchor tags within this div, so simply having the alert executed when the div is clicked won't work for what I need. The website this is on is a search engine using ajax to send information to do_search.php. Within the do_search.php I make pagination decisions based on how many results are found, and if applicable, a next, previous, last, and first link may be made and echoed.

EDIT: I just figured it out, it was my placement of the .next function, since it wasn't created on the initial document load but instead after a result had been returned, I moved the .next function to the success part of the ajax function since that is where the buttons will be created if they need to be, now it works.

Answer

linkyndy picture linkyndy · Jul 6, 2011

Try using the live() command:

$(".bar").live("click", function(){ alert(); });

Because you load your button via AJAX, the click event isn't binded to it. If you use the live() command, it will automatically bind events to all elements created after the page has loaded.

More details, here