1

I am making a browser chat window in Javascript. I want to execute the function that shows and hides the chat when you click the chatbar, but not execute the function when you click on .chat_txt or .chat_new_input

Is it possible to do this?

//JavaScript Show/Hide Function
$('.hidden_box').live("click", function(){ showChat(this); });
$('.active_box').live("click", function(){ hideChat(this); });

$('.chat_txt').click(function(event) {
  event.preventDefault();
});

Here is the syntax for the DIV:

<div id="chat_system_msg_lp" class="chat_box clickable_box hidden_box">
    <div id="chat_system_msg_nick" class="chat_name">system_msg</div>
    <ul id="chat_system_msg_txt" class="chat_txt">
        <li id="46">Hi visitor. We suggest you to sign in/sign up in order 
         to have all the benefits from Live-Pin </li>
    </ul>
    <form class="chat_new_message" name="new_msg">
       <input type="text" placeholder="Enter your message..." 
         class="chat_new_input">
    </form>
</div>
Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Luis
  • 1,067
  • 1
  • 14
  • 25

1 Answers1

2

Use

$('body').on('click', '.hidden_box:not(.chat_box)', function() { showChat(this); });

if you're on jQuery 1.7+. Older jQuery:

$('body').delegate('.hidden_box:not(.chat_box)', 'click', function() { showChat(this); });

Similarly of course for the other one.

edit — I should have explained further. The .live() API was kind-of a bad idea, and since around 1.4 the .delegate() function was definitely preferred. You could still do it with "live" using the same selector, but don't unless you're on a really old version of jQuery.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • I can't use on('click'), just live('click') due to the source of the divs created. – Luis Feb 11 '12 at 20:27
  • 3
    That makes no sense. `live()` is deprecated since jQ 1.7+ in favor of `on()` – elclanrs Feb 11 '12 at 20:30
  • Oh, thanks for the info. Now, I just want to use on
    – Luis Feb 11 '12 at 20:32
  • 1
    @Luis answer updated - the `.on()` and `.delegate()` functions can do the same thing as `.live()` and are the better way to do it. – Pointy Feb 11 '12 at 20:32
  • And also, you're problem is because of this http://stackoverflow.com/questions/1967537/how-to-stop-event-bubbling-with-jquery-live. So if you're no creating elements dinamically, use just `click()` and it should work. – elclanrs Feb 11 '12 at 20:32
  • @Luis Then you use ".hidden_box:not(#boxes .chat_box)". – Pointy Feb 11 '12 at 20:33
  • @elclanrs oh boy you're right :-) Thanks for pointing that out. – Pointy Feb 11 '12 at 20:34
  • @elclanrs This items are created dynamically, that's the main problem. – Luis Feb 11 '12 at 20:36
  • @Pointy I'm sorry, I got confused with your last answer. Can you update the code so when I click on .chat_box works but when i do in `.new_chat_messgae` / `.chat_txt` doesn't? – Luis Feb 11 '12 at 20:38