MogerCS
MogerCS

Reputation: 342

Is it possible to change event bubbling order in js

I have a 3 boxes in my HTML, all the boxes have there own click events. When I click on my child, event bubbling is happening hierarchical order from child to parent C->B->A.

But now I wanted to know more about, whether I can change the event bubbled order to C->A->B.

Once I click on C, event should go from C to A then it should come to B,

Is it possible to shuffle the event bubbling order, I just wanted to learn more about that, Please suggest me

Code

functionA() {
  console.log("A");
}

functionB() {
  console.log("B");
}

functionC() {
  console.log("C");
}
<div (click)="functionA()">Box A
  <div (click)="functionB()">Box B
    <div (click)="functionC()">Box C
    </div>
  </div>
<div>

Upvotes: 1

Views: 746

Answers (1)

humanshado
humanshado

Reputation: 188

There are two ways you can achieve that sequence of events.

First Way: You can attach an event listener to Box C and then call the functions in the order you want. Let's assume your HTML divs look like this:

<div>Box A
   <div>Box B
      <div id='c'>Box C</div>
   </div>
</div>

Notice Box C has an id of 'c'. In your javascript code, declare Box C using its id:

var c = document.getElementById('c');

Define your functions

var funcA = function(){
  console.log("A");
  funcB();
};

var funcB = function(){
  console.log("B");
};

var funcC = function(){
  console.log("C");
  funcA();
};

Notice that funcC calls funcA and then funcA calls funcB. This gives you the sequence C -> A -> B you want. The next thing is to attach a click event listener to Box C with funcC as the callback like so:

c.addEventListener('click', funcC());

Second Way: You can use an onClick event on Box C instead of attaching an event listener like so:

<div>Box A
    <div>Box B
      <div onClick='funcC()'>Box C</div>
    </div>
</div>

In this case, all you need are your functions as defined above and don't need id on Box C.

Upvotes: 1

Related Questions