Frank Martin
Frank Martin

Reputation: 3441

How to select div which was clicked by user from jquery

I am using jquery autocomplete and upon selection of any item, I add a new div with class set to active_chat so this div becomes active. Before adding new div, I remove active_chat from previous divs so only the last added div remains active.

Now I want to give option to users to click any other non-active div and make it active i.e. set its class active_chat. For that I am looking for code to select div which was clicked by user but I don't know how to do that as my code gives all divs and I don't actually know which one was clicked by the user.

Following is my main div which contain all elements

<div class="inbox_chat" id="inboxchat">                        
</div>

Following is jquery I am using to add new div dynamically and setting its class to active_chat

$("#users").autocomplete
({
    select: function (event, ui)
    {
        $('.chat_list').removeClass("active_chat");
        $('#inboxchat').prepend('<div class="chat_list active_chat"><div class= "chat_people"><div class="chat_img"> <img src="mypic.jpg" alt="sometitle"></div><div class="chat_ib"><h5>my name<span class="chat_date">Dec 25</span></h5><p>sometext</p></div></div></div>');
    }
});

Following is the code I am using to select current div which was clicked by the user but it is picking all divs

$(document).on('click', '#inboxchat', function () {
    var clicked = $(this).siblings();
    console.log(clicked);
    alert("now1");
});

When a user clicks any div, I simply want to set active_chat for that div and remove this class from other divs.

EDIT
I am setting active_chat for a div called chat_list

Upvotes: 0

Views: 302

Answers (1)

heyitsvajid
heyitsvajid

Reputation: 1121

Try this if you want it want it to work on any div on the page:

$('div').on('click', function(){
    $("div").removeClass("active_chat");
    $(this).addClass("active_chat");
});

Does this have to work only for divs with class "inbox_chat"? If so, try:

$('div. inbox_chat').on('click', function(){
    $("div").removeClass("active_chat");
    $(this).addClass("active_chat");
});

Upvotes: 1

Related Questions