Kevin Sun
Kevin Sun

Reputation: 173

Jquery .remove() only acts on second click and after

I have a bootstrap popover that pops up after clicking on a notification icon on my page. Part of its functionality is to remove any notification from the popover after clicking on it. Here is an image of the popover with three notifications, for reference:

notifications

However, when I open the notification popover, then click on any of the notifications, the first click won't remove the notification, but the second one will. The click listener is firing both the first and second times (confirmed with logging to console). I checked other questions similar to mine, but none of them had a solution that worked for me. I read up on something about the "focus" but couldn't understand what they meant. Maybe that has something to do with it?

Here is the popover code:

$(document).ready(function(){
  $("#notificationsBell").popover({
    'title' : $('.notifications-title-header').html(), // display:none so it doesn't show up in window
    'html' : true,
    'placement' : 'left',
    'content' : $(".notifications-list").html() // display:none
  });
});

And here is the click listener that is supposed to remove the notification:

$('body').off("click").on("click", ".popover-body .notif-popup-container", function() {
  var notifId = $(this).attr("id");
  $('#' + notifId).remove();
})

I think it has to do with the popover and display:none aspects. This is because I try removing elements elsewhere in the code without display:none and the popover, and it works on the first click. Any insight is appreciated!

Upvotes: 1

Views: 167

Answers (1)

Charbel Sarkis
Charbel Sarkis

Reputation: 81

If the element you're adding a click event listener to. doesn't exist yet that could be a problem.

What's .off btw

Upvotes: 1

Related Questions