dc09
dc09

Reputation: 486

How to fire click event that was attached later before click event attached earlier via jQuery?

//First click handler added via a plugin whose files I do not wish to change
jQuery('.element').click(function(){
console.log('click event 1');
});

//2nd click handler - need this to be executed before the 1st 
jQuery('.element').click(function(e){
e.preventDefault();
e.stopImmediatePropagation();
e.stopPropagation();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<div class="element">Click Here</div>

I have the following code that attaches a click event to some elements:

$('.element').click(function(){
console.log('click event 1');
});

After the above code if executed, the following code attaches 2nd click event handler to the same element:

$('.element').click(function(e){
e.preventDefault();
e.stopImmediatePropagation();
e.stopPropagation();
});

Event though the 2nd block of code has event.preventDefault(),event.stopPropagation(),the first function is executed. How to change the execution order such that the 2nd block of code is executed first on click event?

Upvotes: 0

Views: 63

Answers (1)

mplungjan
mplungjan

Reputation: 178421

So this does not work because the first event handler is executed first

$('.element').on("click", function() {
  console.log('click event not under my control yet');
});

$("#container").on("click", ".element", function(event) {
  // Your logic here to decide whether to allow the original event handler
  var shouldAllowEvent = false /* your condition */ ;

  if (!shouldAllowEvent) {
    event.stopImmediatePropagation();
  }

  console.log('intercepted event')
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div id="container">
  <a href="#" class="element">Click</a><br/>
  <a href="#" class="element">Click</a>
</div>

Let's turn it off

$('.element').on("click", function() {
  console.log('click event not under my control yet');
});

// Step 1: Unbind the existing event handler
$('.element').off("click");

// Step 2: Bind YOUR event handler to the container
$("#container").on("click", ".element", function(event) {
  var shouldAllowEvent = false; // Your condition

  if (!shouldAllowEvent) {
    event.stopImmediatePropagation();
    console.log('Event intercepted and blocked');
  }
});

// Step 3: Re-bind the "original" event handler if you know it. If not, it is not trivial to get it back
$('.element').on("click", function() {
  console.log('click event NOW under my control');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div id="container">
  <a href="#" class="element">Click</a><br/>
  <a href="#" class="element">Click</a>
</div>

Upvotes: 0

Related Questions