Mardoxx Mardoxx - 4 months ago 11
jQuery Question

Javascript Clicks, Taps and Hovers

What I'm trying to achieve is:

On desktop: 1) Hover to bring up overlay 2) Click to activate

On touch: 1) Tap to bring up overlay 2) Tap again to activate

What I've come up with so far is the below. However when using a touch device it fires the both

touchend
event and then the
click
event, this causes the overlay click event to be fired unnecessarily. What's the best way around this, if any?



$(".container > .item").on("mouseenter mouseleave", function(e) {
$(this).toggleClass("hover");
console.log("hover: " + e.type);
});

$(".container > .item > .overlay").on("mouseup touchend", function(e) {
console.log("click: " + e.type);
})

.item {
width: 200px;
height: 200px;
background: red;
display: inline-block;

position: relative;
}

.item.hover > .overlay {
display: block;
}

.overlay {
display: none;
position: aboslute;
top: 0;
left: 0;
height: 100%;
width: 100%;
background: green;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="container">
<div class="item">
<div class="overlay">
</div>
</div>
</div>




Answer

I came up with this, which works rather nicely.

(function() {
  var isTouched = 0;
  var isSecondTouch = 0;
  
  $(".image").on('mouseenter', function(e) {
    $(this).toggleClass("hover");
  });
  
  $(".image").on('mouseleave', function(e) {
    $(this).toggleClass("hover");
    isTouched = 0; // Reset touch
  });

  $(".image").on('touchend', function(e) {   
    if (isTouched) {
      isSecondTouch = 1;
    } else {
      isTouched = 1;
      isSecondTouch = 0;
    }
  });
  
  $(".image .overlay").on("click", function(e) {
    if (!isTouched || (isTouched && isSecondTouch)) {
      console.log("Activated: " + new Date().getTime());
    }
  });

}());
.image {
  width: 100px;
  height: 100px;
  background: grey;
  
  position: relative;
}

.image .overlay {
  display: none;
  postition: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
}

.image.hover .overlay {
  display: block;
  background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="image">
  <div class="overlay">
  </div>
</div>