"Implement a style change to an element upon clicking outside of the specified element defined in an Angular directive

I've implemented SVG items that highlight their corresponding path when a user clicks or hovers over them.

To achieve this, I am utilizing Directives to detect events such as onEnter, onLeave, and Click.

The highlighting works smoothly when I hover over the element (it highlights), and it also stays highlighted when I click on it.

However, the issue arises when I click elsewhere and the highlight remains.

What I aim to do is make the highlight disappear when I click on any other part of the screen.

Below is the logic for my directive:

export class HighlightDirective {
  constructor(private renderer: Renderer2, private el: ElementRef) {}
  clicked = false;
  
  @HostListener('mouseenter') onMouseEnter() {
    this.changeOpacity(1);
  }

  @HostListener('mouseleave') onMouseLeave() {
    if (!this.clicked) {
      this.changeOpacity(0);
    }
  }
  
  @HostListener('click') click() {
    this.changeOpacity(1);
    this.clicked = true;
  }
  
  changeOpacity(opacity: number) {
    this.renderer.setStyle(this.el.nativeElement.nextSibling, 'opacity', opacity);
  }
}

And here's a snippet of the SVG with the Highlight attribute tag:

<g id="b1" transform="translate(-885 -562)">
    <g id="b1select">
        <ellipse id="Ellipse_1" data-name="Ellipse 1" cx="5.3" cy="5.3" rx="5.3" ry="5.3" transform="translate(1309.17 932.12)" fill="none" stroke="#b18802" stroke-width="1"/>
        <text id="B1-2" data-name="B1" transform="translate(1310.67 939.62)" fill="#b18802" font-size="6" font-family="ArialMT, Arial"><tspan x="0" y="0">B1</tspan></text>
    </g>
    <rect appHighlight (click)="openDialog($event)" id="container" width="12" height="11" transform="translate(1308.67 931.62)" fill="rgba(255,255,255,0)"/>
    <path id="b1-3" data-name="b1" d="M1093.763,1595.658v-82.417s5-14.987-18.452-16.644-40.9,2.386-54.093-11.537-132.873-159.193-132.873-159.193-6.456-10.249-24.986-14.661-9.858-17.907-4.728-25.235,39.039-47.23,39.039-47.23" transform="translate(208.67 -656.38)" fill="none" stroke="#efcf2f" stroke-linecap="round" stroke-width="2"/>
</g>

Check out an example on StackBlitz.

Answer №1

document.removeEventListener('mousedown', this.scroll);

The technique I implemented involves removing the scroll event when a mousedown event is triggered. This allows for seamless functionality by using removeEventListener() after initially adding the event listener with addEventListener(). The 'this.scroll' parameter refers to the specific event that will carry out the desired action.

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

When you click on a main category, a list of its corresponding subcategories will

concept image My vision involves having users click on a category from the top menu to display all main cards (parent cards), and then further clicking on a parent card will unveil its corresponding child cards. I've even included an image to help v ...

Encountering difficulty when determining the total cost in the shopping cart

I am currently working on a basic shopping cart application and I am facing an issue when users add multiple quantities of the same product. The total is not being calculated correctly. Here is my current logic: Data structure for Products, product = { ...

AngularJS gender dropdown with a default value of "empty"

I am still new to learning about angular and I am facing an issue with a dropdown menu for gender. I want to add a "--Select--" option, but it ends up duplicating. Below is the code snippet: <td style="font-family: Brandon-Grotesque, Helvetica Neu ...

Determine the overall sum of rows present within this particular tbody section

I am struggling to calculate the total number of tr's within my nested tbody, but I am not getting the correct count. The jQuery code I used is returning a high number like 44 rows instead of the expected 7 rows. Can anyone point out where I might ha ...

Struggling to align text to the far left within a text area using Bootstrap

When I accidentally place my cursor earlier in the text area, it starts writing from that point, leaving some unwanted spaces at the beginning. I prefer it to start from the extreme left, similar to how it behaves in input boxes. Below is the code snippet ...

An Easier Way to Incorporate an Image Insert Button into CKEditor

Having trouble displaying the Insert Image button in CKEditor 4.1.1? Here's my current configuration setup in config.js: CKEDITOR.editorConfig = function( config ) { // Customizing default configuration here. // For more details, check: http: ...

What is the method for applying the action (hide) to every table cell that doesn't include a specific string in its ID?

I have a table with cells containing unique IDs such as "2012-01-01_841241" that include a date and a number. My goal is to filter the table to only display three specific numbers by sending a request and receiving those numbers. Is there a more efficien ...

Why does replacing <input> with <TextField> in Material-UI & React cause the form submission to fail?

Recently, I encountered an issue with my CRUD Todo app's form for adding tasks. Initially built with a basic HTML input and button setup, I decided to enhance the design using Material-UI components. After introducing <TextField> in place of th ...

Why is the Vue Yandex Maps package failing to function in Vue 3 when utilizing the defineCustomElement feature?

I am currently working on 2 different projects in Vue 3 that involve utilizing vue yandex maps: First project: You can view a demo of the first project where Vue Yandex Maps is being used by clicking here. In this project, the package is registered as fo ...

As the div elements stack up and you scroll towards the top or bottom

I am dealing with two nested DIVs that are both scrollable. When I scroll the "inside div" (the green one in the attached file), and reach the bottom of the DIV, it starts scrolling the DIV beneath it. How can I prevent the DIV beneath from scrolling only ...

Executing asynchronous actions with useEffect

Within my useEffect hook, I am making several API requests: useEffect(() => { dispatch(action1()); dispatch(action2()); dispatch(action3()); }, []); I want to implement a 'loading' parameter using async/await functions in the hook ...

Converting objects into CSV format and exporting them using JavaScript

When exporting to CSV, large strings are causing other cells to be rewritten. See the screenshot for the result of the export here. For the code related to this issue, refer to this link. The question is how to prevent large string values in a cell from a ...

Are you familiar with manipulating the JSON data array retrieved from an Ajax response?

Is it possible to handle a response from AJAX request in PHP? I'm not very familiar with JavaScript, so I'm struggling with this one. This is what I have managed to put together: var base_url = 'http://dev.local/westview/public'; $(& ...

What could be causing this jQuery selector to not select any elements?

Here's a simple question with some code that needs troubleshooting: $insides = $('<thead><tr><th><!--Blank space --></th></tr></thead><tbody><tr class="green-row"><td>Opportunities to D ...

Search for every div element and locate the ul element within it. Calculate the total number of table rows present in the ul element. Add this

There is a list on my website with a sublist called .cart-items. This sublist contains a table with multiple rows. My goal is to iterate through each .cart-select item and count the number of tr elements within the cart-items. The count should then be disp ...

What is preventing me from being able to view the contents of the hidden columns in this DataTable?

The issue at hand I am facing a challenge with accessing the content of each cell within my data table. My goal is to retrieve the text of every cell in every row, including the ones that are hidden, in order to print and display all elements accurately. ...

What could be causing my Node application to give a 404 error when making a POST request?

I'm at a loss trying to debug my app for what seems like a simple error, but I just can't locate it. Here is an overview of how my Express app is structured. My routes are set up as follows: var routes = require('./routes'); ... app.g ...

Could anyone provide a breakdown of the code listed below?

Help me unravel the mysteries of Promises! I have a challenge ahead of me. I need to write a function that will display 3000 after 3 seconds, then display 2000 after 2 seconds, and finally 1000 after 1 second. This is what I have so far: 'use strict& ...

Angular does not propagate validation to custom form control ng-select

In my Angular 9 application, I am utilizing Reactive Forms with a Custom Form Control. I have enclosed my ng-select control within the Custom Form Control. However, I am facing an issue with validation. Even though I have set the formControl to be requir ...

Continuously encountering a Login Required message while attempting to upload a file on Google Drive

I am currently developing a chrome extension that is designed to intercept specific downloads, like .doc and .docx files, and automatically upload them to a designated folder in Google Drive. Below is the manifest for this extension: { // Manifest det ...