ab1407
ab1407

Reputation: 11

jQuery on() method not reached

I'm working on a web application in asp.net core and I want that every time a user clicks on a notification, that notification to be marked as read. I've tried to accomplish this by using JavaScript. The code works fine until it reaches this code $("ul").on('click', 'li.notification-text', function (e){...} and I don't understand why. Any advice would be greatly appreciated. Here is what I've tried so far:

$(function () {
    $('[data-toggle="tooltip"]').tooltip();
    $('[data-toggle="popover"]').popover({
        placement: 'bottom',
        content: function () {
            return $("#notification-content").html();
        },
        html: true
    });

    $('body').append('<div id="notification-content" class="form-control" hidden></div>') 

    function getNotifications() {
        var res = "<ul class='list-group'>";
        $.ajax({
            url: "/UserNotification/UnreadNotifications",
            method: "GET",
            success: function (result) {
                if (result.count != 0) {
                    $("#notificationCount").html(result.count);
                    $("#notificationCount").show('slow');
                } else {
                    $("#notificationCount").html();
                    $("#notificationCount").hide('slow');
                    $("#notificationCount").popover('hide'); 
                }
                var notifications = result.notifications;
                notifications.forEach(element => {
                    res = res + "<li class='list-group-item notification-text' data-id='" + element.notificationId + "'>" + element.info + "</li>"; 
                });
                res = res + "</ul>";
                $("#notification-content").html(res);

                console.log(result);
            },
            error: function (error) {
                console.log(error);
            }
        });
    }

    $("ul").on('click', 'li.notification-text', function (e) {  // it does not reach this point
        var target = e.target;
        var id = $(target).data('id');
        console.log("before read");
        readNotification(id, target);
        console.log("after read");
    })

    function readNotification(id, target) {
        $.ajax({
            url: "/UserNotification/MarkAsRead",
            method: "GET",
            data: { notificationId: id },
            success: function (result) {
                getNotifications(); // to update the notification count
                $(target).fadeOut('slow');
            },
            error: function (error) {
                console.log(error);
            }
        })
    }


    getNotifications();
});

Upvotes: 1

Views: 78

Answers (1)

Joy Zalte
Joy Zalte

Reputation: 101

Change From :

 $("ul").on('click', 'li.notification-text', function (e) { 

To :

$(document).on('click', 'ul > li.notification-text', function (e) { 

Upvotes: 2

Related Questions