When I hover over the content, the image displayed in the tooltip is causing a flickering effect

Dealing with Angular in this situation, my goal is to have an image or video displayed inside a tooltip when hovering over specific content. However, there seems to be a flickering effect before the image renders, making the transition less smooth compared to using text instead of an image. How can I resolve this issue?

I am attempting to set the image source within an input for the tooltip component. The code snippet below demonstrates how this is implemented:

app.component.html

<button awesomeTooltip="Hello World!"  image="https://imgplaceholder.com/420x320/ff7f7f/333333/fa-image">Hi there, I have a tooltip</button>

tooltip.component.ts

import { Component, Input } from '@angular/core';
import { animate, style, transition, trigger } from '@angular/animations';

@Component({
  selector: 'awesome-tooltip',
  styleUrls: ['./tooltip.component.css'],
  templateUrl: './tooltip.component.html',
  animations: [
    trigger('tooltip', [
      transition(':enter', [
        style({ opacity: 0 }),
        animate(300, style({ opacity: 1 })),
      ]),
      transition(':leave', [
        animate(300, style({ opacity: 0 })),
      ]),
    ]),
  ],
})
export class AwesomeTooltipComponent {

  @Input() image=''
  @Input() text = '';
}

tooltip.component.html

<div @tooltip>
   <img [src]="image" width="20px" height="30px">
   <!-- Hello -->
</div>

tooltip.directive.ts

import { ComponentRef, Directive, ElementRef, HostListener, Input, OnInit } from '@angular/core';
import { Overlay, OverlayPositionBuilder, OverlayRef } from '@angular/cdk/overlay';
import { ComponentPortal } from '@angular/cdk/portal';

import { AwesomeTooltipComponent } from './tooltip.component';

@Directive({ selector: '[awesomeTooltip]' })
export class AwesomeTooltipDirective implements OnInit {

  @Input('awesomeTooltip') text = '';
  @Input('image') image = '';
  private overlayRef: OverlayRef;

  constructor(private overlay: Overlay,
              private overlayPositionBuilder: OverlayPositionBuilder,
              private elementRef: ElementRef) {
  }

  ngOnInit(): void {
    const positionStrategy = this.overlayPositionBuilder
      .flexibleConnectedTo(this.elementRef)
      .withPositions([{
        originX: 'center',
        originY: 'top',
        overlayX: 'center',
        overlayY: 'bottom',
        offsetY: -8,
      }]);

    this.overlayRef = this.overlay.create({ positionStrategy });
  }

  @HostListener('mouseenter')
  show() {
    const tooltipRef: ComponentRef<AwesomeTooltipComponent>
      = this.overlayRef.attach(new ComponentPortal(AwesomeTooltipComponent));
    tooltipRef.instance.text = this.text;
    tooltipRef.instance.image = this.image;
  }

  @HostListener('mouseout')
  hide() {
    this.overlayRef.detach();
  }
}

The stackblitz link can be accessed here:

The desired outcome includes:

  • The ability to pass an image URL through the tag on which the tooltip should appear.
  • The tooltip displaying the specified image within it.

Answer №1

Here is a breakdown of how the overlay functions:

  • Upon hovering over the button, the overlay becomes visible
  • Moving away from the button causes the overlay to hide

The flickering issue occurs due to an unresolved situation:

  1. Hovering over the lower part of the button displays the overlay
  2. However, since the overlay starts from the middle of the button, technically you are now hovering over the overlay (not the button), causing it to disappear
  3. As soon as the overlay disappears, it reverts back to step #1 above...

This cycle repeats, leading to the flickering effect you observe.

To address this problem, include the code snippet below in your tooltip.component.css file to position the overlay beneath the button and prevent this recursive flickering:

::ng-deep .cdk-overlay-connected-position-bounding-box{top:60px !important; position:absolute;}

UPDATE: For larger buttons, adjust the top value accordingly to ensure the overlay begins beneath the button without any overlap. View a demo here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ensure that the csrf token is included on all routes

I have successfully implemented CSRF protection in my Node.js web application, but I am facing an issue where the CSRF token is only attached if I visit the /login route. How can I ensure that the CSRF token gets implemented on every route without causing ...

As the Page Expands, Elements Shift into New Positions

I'm currently focused on enhancing the accessibility of my web pages. A challenge I've encountered is that when I expand the width of my page, the elements appear to shift further down the screen. It seems like this issue may be related to settin ...

Caution: Prop type validation failed due to an invalid value being passed to ForwardRef(Slider)

Currently, I'm in the process of building a Material UI range Slider with two values. It functions correctly if initialized like this: const [value, setValue] = React.useState([5,20]); const [value, setValue] = React.useState([val]); const handl ...

Generating a new POST header

I have encountered a challenge: I need to transfer an array to another page without using AJAX. My goal is to either redirect the user to the new page or open a popup displaying the new page, all while ensuring the array data is sent via a POST request. C ...

Using React Material UI icon within an auto complete feature

https://i.stack.imgur.com/W3CmF.png I am struggling to incorporate the target icon into the autoComplete component. After reviewing the documentation, I have been unable to find a solution. In TextInput, a similar outcome can be achieved by implementing ...

Selection auto-closing feature

I am currently working on a button that generates a dropdown menu with various categories to choose from. I would like the dropdown to automatically close when I click outside of it, similar to how a lightbox or modal popup works on a webpage. Currently, I ...

Implementing an API call using Redux Saga within a React application

I have been diving into learning saga by following a tutorial on Medium and trying to implement it in StackBlitz. I encountered a path issue initially, managed to fix it after several attempts, but now a different problem has come up. Despite searching on ...

Tips for achieving a dimmed content effect on Semantic UI React within a NextJS project

I'm currently facing an issue with incorporating dimmed content into the Semantic UI React sidebar on Next.js... Here is the example of dimmed content on Semantic UI: https://i.sstatic.net/5dOGK.png This is the layout code I am using: import React, ...

What steps can be taken to override the property overflow:hidden specifically for a custom tooltip design

I am facing a challenge with overriding the property overflow:hidden in the parent td element. https://i.stack.imgur.com/HKcvn.png This issue is related to my tooltip, which ideally should be displayed beneath the td element: Code snippet for the toolti ...

It appears that Yarn is having trouble properly retrieving all the necessary files for a package

Recently, I encountered a strange issue in our project involving 3 microservices, all using the exceljs library. Two of the microservices successfully download all necessary files for this package through yarn. However, the third microservice is missing ...

What is the best way to upload an image along with optional information using multer?

How to send a File object from the frontend using React and FormData Output of files https://i.sstatic.net/gp61r.jpg Upon uploading a file, I am able to access the object in Multer and Express-Upload console.log(req.files.productImages) [{ &qu ...

Understanding the usage of jQuery transitionend to prevent interruptions in CSS animations

I found a similar thread on StackOverflow but I'm struggling to apply it in my current scenario. The Setup (Welcome Ideas) I've developed a jQuery slider that will have multiple instances on one page, each containing an unknown number of childr ...

A guide on updating object values within an array using map in React

Is there a method to calculate the total sum of specific values from an array of objects? Example array: const exampleArray = [ {item_id: 1, quantity: "3"}, {item_id: 2, quantity: "5"}, {item_id: 3, quantity: "2"} ] In this case, I want to add up the qua ...

Why isn't the externally loaded JS file executing properly?

My javascript code functions properly when it's embedded within the HTML file. However, I encounter issues when I try to import it externally. The Google Developer Tools indicate that the file has been loaded successfully, but there seems to be no vis ...

Finding a particular movie in React

import { useState,useEffect } from 'react' import React from 'react' import MoviesItem from './MoviesItem' const Movies = ({search}) => { const [movie, setMovie] = useState([]) const fetchData = async() => ...

The challenge of handling multiple save conflicts in asynchronous Mongoose operations

My Node/Mongoose/Socket.io setup is presenting a challenging logic issue. Imagine a scenario where the Server model is frequently accessed and updated simultaneously in my application. db.Server.findOne({_id: reference.server}).exec(function(error, se ...

I exclusively use CSS for my tooltips, no images involved

I created some CSS code for a tooltip element .toolTip{ display:inline; position:relative; } .toolTip:hover:after{ background: #333; background: rgba(0,0,0,.8); border-radius: 5px; bottom: 26px; color: #fff; content: attr( ...

Having issues with the user registration form in the MERN stack

Encountering a 404 Error in MERN Stack Description: Struggling with a persistent 404 error while trying to access my MERN stack application. Despite exhaustively checking all potential sources of the error, the root cause continues to elude me. Here is ...

Performance of obtaining image data

Is anyone else experiencing a significant lag when trying to retrieve the state of a single pixel on the canvas? Take a look at my JS code below: var state = ctx.getImageData(x,y,1,1).data; state = 'rgba(' + state[0] + ',' + state[1] ...

Guide on bundling an Angular 6 project with ECMA6 JavaScript (polymer js) into a consolidated package

I am facing an issue with my Angular6 application that relies on external JS files written in ECMA6 (e.g. polymer). When I build the application using Angular CLI, it fails to transpile these external ECMA6 JS files, causing the application to not load in ...