Blauharley
Blauharley

Reputation: 4246

Ionic Event-LIsteners on-hold/on-tab Parent/Child Issue

In an cordova/ionic app there is a parent-div on which on-hold-listener is attached and a child-div which subscribed for on-tab events like so:

<div on-hold="doSomething()">
   <div on-tap="doSomething2()">...</div>
</div>

From time to time it works but there have been situations in what on-tab was executed instead of on-hold when pressing time was bigger than 500ms.

Might this be done in a better way? Please take into consideration that child-div fills out parent completely and it should remain so.

Thanks in advance.

Upvotes: 0

Views: 1024

Answers (2)

Blauharley
Blauharley

Reputation: 4246

After experimenting with stopPropagation I came up with following answer that needs setTimeout to check for mouse/cursor is being holded.

When just clicking on the child-div(red) doSomething2 is alerted whereas holding onto child-div alerts doSomething of parent instead:

var holding = false;
var secondFunctionCall = false;

document.getElementById("c1").addEventListener('mousedown', function(e) {
 
  holding = true;

  setTimeout(function(){
    if(holding){
      secondFunctionCall = false;
      alert("calling doSomething()");
    }
  },500);

}, false);

document.getElementById("c2").addEventListener('mousedown', function(e) {

  holding = true;
  secondFunctionCall = true;

}, false);

document.getElementById("c2").addEventListener('mouseup', function(e) {

  holding = false;

  if(secondFunctionCall){
    alert("calling doSomething2()");
  }

}, false);
#c2 {
  width: 200px;
  height: 200px;
  background-color: red;
}
#c1 {
  width: 220px;
  height: 220px;
  background-color: yellow;
}
<div id="c1">
  <div id="c2">
  </div>
</div>

When transfering this code into a cordova-app mouse-event types have to be replaced by touch-event types as it is answered here.

Upvotes: 0

Arnaud Bertrand
Arnaud Bertrand

Reputation: 1461

When you have a div parent of another div the events are propagated. You can try by yourself here:

.c2 {
  width: 200px;
  height: 200px;
  background-color: red;
}
.c1 {
  width: 220px;
  height: 220px;
  background-color: yellow;
}
<div class="c1" onclick="alert('squareParent');">
  <div class="c2" onclick="alert('squareChild');">
  </div>
</div>

To avoid this you need to stop the propagation:

document.getElementById("c1").addEventListener('click', function(e) {
  alert("c1");
}, false);

document.getElementById("c2").addEventListener('click', function(e) {
  alert("c2");
  e.stopPropagation();
}, false);
#c2 {
  width: 200px;
  height: 200px;
  background-color: red;
}
#c1 {
  width: 220px;
  height: 220px;
  background-color: yellow;
}
<div id="c1">
  <div id="c2">
  </div>
</div>

You could check more about javascript bubble if you want more information.

Upvotes: 1

Related Questions