Search code examples
angularprimeng

PrimeNg Tooltip disappearing on mobile and tablet when touch released even with life set or hidedelay set


I'm configuring a tooltip for a custom button and assigning a method to a (touchstart) event, because hover event for primeng tooltip is not working in tablet or mobiles.

This is the code for the method:

onTouch() {
   this.tooltip.hideDelay = 5000;
   this.tooltip.show();
}

The problem is that the delay is not working, when I release the touch the tooltip disappear. I need the tooltip to remain after touch is released for 5 seconds.

How should I do it? Tried timeout and left properties but not working.


Solution

  • modify your template to handle both touchstart and touchend events:

    <button pTooltip="Your tooltip text" 
            #tt="pTooltip"
            (touchstart)="onTouchStart($event)"
            (touchend)="onTouchEnd()">
        Button Text
    </button>
    

    Then in your component, implement the logic to manage the tooltip visibility:

    export class YourComponent {
      @ViewChild('tt') tooltip: any;
      private tooltipTimer: any;
    
      onTouchStart(event: TouchEvent) {
        event.preventDefault(); // Prevent default touch behavior
        this.tooltip.show();
      }
    
      onTouchEnd() {
        // Clear any existing timer
        if (this.tooltipTimer) {
          clearTimeout(this.tooltipTimer);
        }
        
        // Set new timer to hide tooltip after 5 seconds
        this.tooltipTimer = setTimeout(() => {
          this.tooltip.hide();
        }, 5000);
      }
    
      ngOnDestroy() {
        // Clean up timer when component is destroyed
        if (this.tooltipTimer) {
          clearTimeout(this.tooltipTimer);
        }
      }
    }
    
    • Use both touchstart and touchend events to better control the tooltip behavior
    • Prevents the default touch behavior which might interfere with the tooltip