Conceal the element after a set number of milliseconds when the mouse exits the element

I'm having trouble creating this observable. In my Angular application, I have an element that can be hidden. The requirement is that if the user moves the mouse away from the element and does not return within 500ms, the element should hide.

The visualization looks like this:

onleave --x-------x------------------------>
onenter -----x----------------------------->
                  <--500ms-->
_________________________________________
hide    ---------------------x------------->
const leave$ = fromEvent(this.selector.nativeElement,"mouseleave");
const enter$ = fromEvent(this.selector.nativeElement,"mouseenter");

const hide$ = // ToDo: implement logic

EDIT:

I've created an observable, but it's not functioning as expected:

const leave$ = fromEvent(this.backgroundSelector.nativeElement, "mouseleave");
const enter$ = fromEvent(this.backgroundSelector.nativeElement, "mouseenter");

const hide$ = leave$.pipe(
      mergeMap(event =>
          of(event).pipe(
                delay(500),
                takeUntil(enter$)
          )
      )
);

hide$.pipe(takeUntil(this.destroy$)).subscribe(_ => this.hideSelector());

The problem is that the element only hides when I return with the mouse cursor after 500ms.

Answer №1

If you want to enhance user experience by delaying the response on mouse leave, consider utilizing the debounceTime operator in RxJS. The official documentation explains its workings.

DebounceTime filters out emitted values that occur too quickly after each other

When dealing with mouseenter and mouseleave events, it's important to manage the timing of emitted values properly. To achieve this, you can make use of the switchMap operator, which enables discarding inner observable emissions.

const main = document.getElementById('main');
const content = document.getElementById('content');    

fromEvent(main, 'mouseenter')
.pipe(   
   switchMap(event => {
     content.style.display = 'block';
     return fromEvent(main, 'mouseleave').pipe(debounceTime(500));
}))
.subscribe(val => {
  content.style.display = 'none';
});

To see an implementation example, check out the code on Stackblitz

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

Is it possible to use ng-bootstrap with vertical tabs?

I'm experimenting with displaying ng-Bootstrap tabs vertically, but the provided example doesn't quite fit my needs. I'm envisioning a layout similar to what I've sketched in the diagram. Do you think it's achievable? Any suggestio ...

The Art of Angular Architecture: Transmitting Information from Parent to Child

Exploring the concept of templates within a template in the example below... @Component({ selector: 'component-a', template: `<div> <component-b></component-b> </div>` }) Should component-b share a s ...

Is there a way to programmatically control a Bootstrap Dropdown in Angular?

Need help with opening and closing a Dropdown in my View using my typescript class. Any suggestions on how to achieve this? Appreciate any assistance! <div ngbDropdown class="d-inline-block"> <button class="btn" id=&quo ...

Unit testing subscription inside an Observable in Angular 4: A step-by-step guide

I'm currently testing a service that is being used in my Angular CLI project. I've managed to test all the functions except for those with a subscribe method, which is causing some issues. I would appreciate any guidance on how to properly test t ...

Exploring depths with Typescript recursion

I'm attempting to implement a recursive search in Typescript, but I am encountering an issue where TS is unable to determine the return type of the function. function findDirectory( directoryId: Key, directory: Directory, ) { if (!directory) ret ...

Develop a PDF generator in ReactJS that allows users to specify the desired file name

Is there a way to customize the file name of a generated PDF using "@react-pdf/renderer": "^2.3.0"? Currently, when I download a PDF using the toolbar, it saves with a UID as the file name (e.g., "f983dad0-eb2c-480b-b3e9-574d71ab1 ...

When I delete the initial element from the array, the thumbnail image disappears

Using react-dropzone, I am attempting to implement image drag and drop functionality. The dropped image is stored in the React state within a files array. However, a problem arises when removing an image from the array causing the thumbnails of the remain ...

send image back to Angular component from server response

I'm extremely close to achieving my goal. The server is successfully returning the image and sending it in the response. Now, the challenge lies in getting my angular component to properly display it. Let me share what I have done so far: Firstly, h ...

Ensuring consistent column widths in tables using Bootstrap 5 and Angular

In my angular application using Bootstrap 5, I have a table structured like this <table> <thead> <tr> <th [ngClass]="{'d-none':prop1==0}"></th> <th [ngClass]="{'d-none':prop2==0} ...

There was an unhandled rejection error stating: "TypeError - Unable to access property 'push' as it is undefined"

I am encountering an issue while trying to create a function that returns all indexes of an array. I'm not sure what mistake I might be making, as I keep getting an error stating that push cannot be used due to an undefined value. Here's the cod ...

Develop a prototype function in ES6/ESNext with a distinct scope (avoid using an inline function)

Consider the following example: class Car { constructor(name) { this.kind = 'Car'; this.name = name; } printName() { console.log('this.name'); } } My goal is to define printName using a differe ...

Upon clicking the button, the Angular Mat-Table with Reactive Forms fails to display any data, instead adding a blank row accompanied by errors

When the AddRow_click() function is executed, I populate the insuranceFormArray and assign its values to the datasource. However, after adding an entry, an empty row appears in the table, and error messages are displayed in the console. Only a subset of th ...

Identify all elements that include the designated text within an SVG element

I want to target all elements that have a specific text within an SVG tag. For example, you can use the following code snippet: [...document.querySelectorAll("*")].filter(e => e.childNodes && [...e.childNodes].find(n => n.nodeValue ...

Encountering a Typescript error while attempting to iterate through Enum keys for generating JSX components

I'm really struggling with this problem. Here's a simple enum I have: export enum depositTypes { ACH = 42, Wire = 36, Check = 3, Credit = 2, } I'm trying to create option tags for a select element, like so: Object.keys(depositTyp ...

Angular 5 - Error: Uncaught ReferenceError: req variable is not defined

After upgrading my Angular project from version 4.4.3 to 5, I made sure to update all angular packages to the latest Angular 5.0.0 as per the guidelines provided. Additionally, I updated the angular CLI to version 1.5.0. However, ever since this update, I ...

What is the best way to define the typings path for tsify?

My TypeScript sources are located in the directory: src/game/ts The configuration file tsconfig.json can be found at: src/game/ts/tsconfig.json Additionally, the typings are stored in: src/game/ts/typings When running tsc with the command: tsc --p s ...

Showing error messages in Angular when a form is submitted and found to be invalid

My form currently displays an error message under each field if left empty or invalid. However, I want to customize the behavior of the submit button when the form is invalid. <form #projectForm="ngForm" (ngSubmit)="onSubmit()"> ...

What might be preventing combineLatest from executing?

Currently, I am attempting to run a block of code utilizing the combineLatest function. Within my translation library, there exists an RXJS Observable that is returned. Imported as individual functions are combineLatest, map, and tap. combineLatest(this. ...

Adding a custom role in Angular TypeScript in Microsoft AppInsights is a straightforward process that can provide valuable

I have an angular project where I am looking to incorporate AppInsight with custom telemetry (role). The project is built in Angular using TypeScript, and I successfully integrated appinsights by following this tutorial. However, when attempting to add cus ...

Why is the name 'console' not being recognized? What could be causing this issue?

The code snippet below illustrates a TypeScript error found at LINE 4: import {Message} from './class/message'; function sendPayload(payload : Object) : any{ let message = new Message(payload); console.log(message); // LINE 4 } The er ...