0

I've got this: http://jsfiddle.net/G3VjC/

which is simply:

$(document).ready(function() {

$(document).on('click','#btn',function(){
    console.log('ran btn');
});
$(document).on('click','#containerdiv',function(){
    console.log('ran div');
});

});

But when clicking the button is run the btn JS and the container JS (see console log).

How can I separate them?

thanks

peter88uk
  • 297
  • 1
  • 5
  • 22

4 Answers4

4

use stopPropagation()

$(document).on('click','.meee',function(e){ // add event as argument
    console.log('ran btn');
    e.stopPropagation()
});
Luca Rainone
  • 16,138
  • 2
  • 38
  • 52
1

Try this

$(document).ready(function() {
    $(document).on('click','#containerdiv',function(){
        console.log('ran div');

    });

    $(document).on('click','.meee',function(){
        console.log('ran btn');
        return false;
    });
});

Demo

Amit
  • 15,217
  • 8
  • 46
  • 68
  • returning false is not always the best option, see: http://stackoverflow.com/questions/1357118/event-preventdefault-vs-return-false – cernunnos Sep 24 '13 at 10:19
0

Or try this:

$(document).ready(function() {
    $('#containerdiv').click(function(){
        console.log('ran div');
    });

   $('.meee').click(function(e){
           e.stopPropagation();
           console.log('ran btn');
   });
});

As chumkiu already said, just use stopPropagation()

adcelis
  • 66
  • 4
0
$(document).on('click','#btn',function(e){
e.stoppropagation();
var target = $(e.target);
if(!target.attr('id') == 'btn'){
 e.preventDefault();
 $(target.find("#btn)).trigger("click")
}
//any additional logic if the target was of the intended type.
});
Ryan
  • 295
  • 2
  • 8