0

I have a page with a lot of e.stopPropagation so what I decided I would do was to create a function. here is code

function stopProp(name) {
 if($(e.target).hasClass(name)) {
   e.stopPropagation();
   }
 }

Though each time in console it does not seem to work at all and says stopProp is undefined.

Here is the actual JS I am trying to turn into a function

$('#chatting').on('click','.chatheader',function(e){
     if($(e.target).hasClass('setting')) {
         e.stopPropagation();
      }
    }
});

Anyone can help me to figure out why this is not working and how I should go about this? I figured it would be fairly easy just to change to a function so I can easily write stopProp('setting');though that is not the case here.

EasyBB
  • 6,176
  • 9
  • 47
  • 77

2 Answers2

1

The handler of the click event should return with one single argument which will be the event. So you should have a function that returns an event, for example like this :

$('#chatting').on('click','.chatheader',stopProp('setting'));

function stopProp(name) {
  return function(e) {
    if($(e.target).hasClass(name)) {
      e.stopPropagation();
    }
  }
}
Samuel Caillerie
  • 8,259
  • 1
  • 27
  • 33
  • Can you please see my comment to the other answer? As I want to know how to write the function of the .on() to do what I need to do for that specified element – EasyBB Apr 29 '13 at 10:46
1

You need to pass the event object to the stopProp method.

function stopProp(e) {
    if($(e.target).hasClass(e.data.className)) {
        e.stopPropagation();
    }
}

Then

$('#chatting').on('click', '.chatheader', {className: 'setting'}, stopProp);

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • Ok so this looks very strange, sorry. I'd like to do something within the on click like so. `$('#chatting').on('click','.chatheader',function() { $(this).fadeOut(); });` So how would I do it like you said? `$('#chatting').on('click', '.chatheader', {className: 'setting'}, stopProp,function(){ $(this).fadeOut(); });`? – EasyBB Apr 29 '13 at 10:43
  • Use `$('#chatting').on('click', '.chatheader', {className: 'setting'}, stopProp).on('click', function(){ $(this).fadeOut(); });` – Arun P Johny Apr 29 '13 at 10:50