0

I have an anchor tag that when is clicked displays more items, after display those items another anchor appears and collapse those items again. I have this script that search a string inside an attribute called evitd in the anchor tag, the string value is ('expand_collapse') when it finds the value triggers an alert, then displays more items and the collapse anchor appears but the script is not working the second time even tho the anchor has the attribute evtid with the value 'expand_collapse'. Any suggestion will be kindly appreciated

$(document).ready(function(){
       $('.ms-cal-nav').each(function () {
       var $this = $(this);
       $this.on("click", function () {
             if ($(this).attr('evtid').indexOf('expand_collapse') > -1) {
            alert("hello");
     
             }
         });
    });
});
<div class="ms-acal-ctrlitem" _expand="expand"><a href="javascript:void(0);" class="ms-cal-nav" evtid="expand_collapse"><img border="0" width="9" height="7">7 more items</a></div>
kazzius
  • 9
  • 2
  • 8
  • Look into event delegation. – crush Aug 17 '15 at 20:33
  • 3
    possible duplicate of [Event binding on dynamically created elements?](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – crush Aug 17 '15 at 20:33

1 Answers1

0

The jQuery documentation has a good explanation of how to do this - they call them "Delegated Events". You register your listener on some static ancestor element (like body, but preferably something closer the elements you want to monitor) and then listen for the event on descendant elements. This enables you to handle events on dynamically added elements.

$(document).ready(function(){
  $('body').on('click','.ms-cal-nav', function () {
     if ($(this).attr('evtid').indexOf('expand_collapse') > -1) {
        alert("hello");
     }
  });
});

Note: I also removed your .each() call as it was unnecessary.

Peter
  • 12,541
  • 3
  • 34
  • 39