0

I have a dynamic carousel banner on my homepage (I have no control over the html expect I can add the href, image ref and I can add an id to the a link for each carousel banner) I can add an an event to the first carousel banner but not the others. I think it's because the html doesn't exist for the banners when the document is loaded execpt the first one as the carousel banner is dynamic and changes every couple of seconds. I've added an id to the second banner of testID and tried the below code:

      $(document).ready(function(){
      $('#testID').click(function(){
      _gaq.push(['_trackEvent', 'cbanner', 'IDtest',$(this).attr('href'),0,true]);
       });
       });

But the onclick event is still not working.

Thanks

user3120015
  • 171
  • 4
  • 5
  • 16
  • possible duplicate of [Event binding on dynamically created elements?](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – dsgriffin Mar 24 '14 at 10:08

1 Answers1

3

Since your buttons created dynamically to the DOM, the click event will not be available for these buttons. In this case, event delegation will help you to attach that event.

Try this

$(document).on('click','#YourDynamicButtonID',function(){

});
Sridhar R
  • 19,414
  • 6
  • 36
  • 35