0

I am listening for click events on the class notification-link:

$(document).ready(function(){
    $('.notifications-link').click(
        function(){
            $('.notifications-popup').addClass('show')
        }
    )
});

Works fine. The problem is, if I append a new Element with the class notification-link to the DOM, jQuery doesn't listen for it = if you clicked on the appended Element, nothing happens.

How can I fix that?

jonhue
  • 1,085
  • 1
  • 15
  • 47

2 Answers2

1

instead of

$('.notifications-link').click(function(){...})

use

$(document).on("click", ".notifications-link", function(){...});

this way you're attaching the event to the document and then checking to see if the click landed on ".notifications-link" and will work will all newly added ".notifications-link"'s

I wrestled a bear once.
  • 19,489
  • 16
  • 63
  • 110
0

You need to use event delegation for the events to work on the elements added via JS.

$(document).ready(function () {
    $('body').on('click', '.notifications-link', function (e) {
        $('.notifications-popup').addClass('show');
    });
});

For detailed explanation about how Jquery event method like on, click etc works please check this post: http://elijahmanor.com/differences-between-jquery-bind-vs-live-vs-delegate-vs-on/