Search code examples
javascriptjqueryclicklisteneronclicklistener

javascript, jQuery: How to re-listen for click events


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?


Solution

  • 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