Reetika
Reetika

Reputation: 1237

Close button on chat box header is not working

I make a chat application with static users. and on click the user , it opens a chatbox.But the close button on that chatbox is not working.

I'm using jQuery to implement this.

$(document).ready(function() {
  $('a').click(function(e) {
    e.preventDefault();
    var targetUser = ($(this).html());
    $(document).data('chat.targetUser', targetUser);
    var user = '<div class="user open" id="' + targetUser + '"><header><div class="status"></div><div class="header-text">' + targetUser + '</div><div class="close">&times;</div></header><div class="message-area"></div><div class="input-area"><input type="text" id="input" /></div></div>';
    $('#chat').append(user);
    $('#chat').find(".close").click(function() {
      $(this).closest(".user open").hide();
    });
  });
});

Upvotes: 1

Views: 491

Answers (3)

anna
anna

Reputation: 595

console.log($('#chat').find(".close")); to find out if the selector works

$( "#chat .close" ).on( "click", function() {
    $(this).closest(".user open").hide();
});

Upvotes: 0

Neel
Neel

Reputation: 11741

Try below code :-

 $('#chat').on("click",  ".close" , function(){
            $(this).closest(".user open").hide();
        });

For more information :-

https://learn.jquery.com/events/event-delegation/

Event delegation refers to the process of using event propagation (bubbling) to handle events at a higher level in the DOM than the element on which the event originated. It allows us to attach a single event listener for elements that exist now or in the future.

Upvotes: 0

Dhaval Marthak
Dhaval Marthak

Reputation: 17366

As you're appending elements to DOM at runtime, You have to try event delegation here:

$('#chat').on("click",".close",function(){
      $(this).closest(".user open").hide();
});

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

Upvotes: 5

Related Questions