Max Frai
Max Frai

Reputation: 64276

JQuery event binding

I'm loading from DB some html (using ajax post request), it looks like:

<div id="slides_control">
   <div>
      <a href="#"></a>
   </div>
</div>

With html I also load JS-code:

<script>
$('#slides_control a').bind('click', function() {
   alert('achtung');
});
</script>

Script goes right after the html (in received data).

But when I click at some link inside new html, I don't see the alert. What's wrong?


I also tried to bind it after ajax ended:

$.post('page.php', {}, function(data) {
    document.write(data);
    $('#slides_control a').bind('click', function() {
       alert('achtung');
    });
});

Didn't help me.

Upvotes: 0

Views: 181

Answers (3)

Ortiga
Ortiga

Reputation: 8814

You probably running bind function before your html has been loaded, so it does not find element

So, put your code to run on dom load:

$(function(){
    $('#slides_control a').bind('click', function() {
       alert('achtung');
   });
}):

Upvotes: 2

hungryMind
hungryMind

Reputation: 6999

execute this script when data is loaded. You are executing this script before data is loaded.

Upvotes: 0

Naftali
Naftali

Reputation: 146300

Try wrapping the jQuery call:

<script>
$(function(){
   $('#slides_control a').bind('click', function() {
      alert('achtung');
   });
});
</script>

Upvotes: 0

Related Questions