Uzumaki Naruto
Uzumaki Naruto

Reputation: 753

e.stopPropagation(); in a custom function

Description :

Following Code works as it should

$("body").on("click","#grumpy",function(e){

// perform some thing

 e.stopPropagation();

});

but if I create a custom function and if I want to stopPropagation() in that it does not work.. e.g

function myFunction()
{
   // do some work

 e.stopPropagation();
}

MY CODE

echo '<div class="recent_notice_in_side shake" id = "notice_no_'.$notice_id.'" onclick = "notice_expand(this.id)">
// other divs...

</div>';

how can achieve e.stopPropagation(); in a custom function I have searched Google but couldn't find how to do this in custom functions.

Upvotes: 0

Views: 1277

Answers (2)

D.T.
D.T.

Reputation: 350

You can do this by creating a click event of yours and passing in the 'e' to your function in the actual click event.

var e = jQuery.Event( "click" );
 myFunction( e );

Usage of created event can be handled in jquery itself. Below code demonstrates the same :

$(function () {
      var myFunction = function (e) {
          e.stopPropagation();
      };
      $("input[type=button]").click(function () {
          var e = jQuery.Event("click");
          myFunction(e);
      });

in HTML

<input type="button" value="Stop Propagation" />

Upvotes: 0

Barmar
Barmar

Reputation: 782693

Your named function needs to take a parameter e, just like the anonymous function does:

function myFunction(e) {
    // do some work
    e.stopPropagation();
}

$("body").on("click", "#grumpy", myFunction);

Upvotes: 3

Related Questions