Tips for selecting specific regions on an Angular SVG map

For my Angular TypeScript project, I included a map. Does anyone know how to create a select region on the map?

Click here for StackBlitz

Here is the jsFiddle code link

CSS styles here


p {
    font-size: 12px;
}

#core {
    fill: #ff4f81;
    animation: pulse1 1.5s ease-in-out infinite;
}

#radar  {
    fill: #F99EAD;
    animation: pulse2 1.5s ease-in-out infinite;
}

@keyframes pulse1 {
    0% {
        opacity: 0;
        transform: scale(0);
    }

    30% {
        opacity: 1;
        transform: scale(1.5);
    }

    60% {
        opacity: 1;
        transform: scale(2);
    }

    100% {
        opacity: 0;
        transform: scale(2);
    }
}

@keyframes pulse2 {
    0% {
        transform: scale(1, 1);
        opacity: 0;
    }

    50% {
        opacity: 1;
    }

    100% {
        transform: scale(6, 6);
        opacity: 0;
    }
}
.row-wrap {
    text-align: center;
    float: left;
    margin: 0 10px;
}

.row-middle {
    font-size: 30px;
    color: #0E76FE;
    font-weight: 700;
}

.row-middle-two {
    font-size: 17px;
    color: #808490;
}

.row-middle-three {
    font-size: 14px;
    color: #9DA2AE;
}

.row-bottom-small {
    font-size: 10px;
    color: #B9C0CD;
}

.row-top-small {
    font-size: 10px;
    color: #B9C0CD;
}

.row-bottom {
    color: #A3A9B5;
    font-size: 12px;
}

.row-top {
    color: #A3A9B5;
    font-size: 12px;
}

Answer №1

Integrating with angular | adjust

To incorporate this into Angular, utilize its (Angular's) lifecycle hooks. Specifically, for your scenario, employing ngAfterViewInit in your appComponent would be ideal. Certain modifications will be necessary from the previously provided code due to typescript limitations regarding style properties on elements.

Here is a live demonstration, along with the relevant code displayed below

ngAfterViewInit() {
    let selectedArea = null;
    let areas = document.querySelectorAll<SVGElement>('path');
    areas.forEach((area) => {
      area.addEventListener('mouseover', function () {
        area.style.fill = 'red';
      });
      area.addEventListener('mouseout', function () {
        area.style.fill = '';
      });
      area.addEventListener('click', function () {
        console.log(selectedArea);
        if (selectedArea) {
          document.querySelector<SVGElement>(`#${selectedArea}`).setAttribute('class', 'st0');
        }
        if (selectedArea !== area.id) {
          selectedArea = area.id;
          area.setAttribute('class', 'selectedArea');
        }
      });
    });
  }

The solution depends on your specific requirements. To highlight a region on hover, add the following CSS:

path:hover { fill: red; }

For a more customizable approach that allows for user choice retention, JavaScript can be used. Here is a basic implementation (which stores the choice in a variable). I have introduced a class selectedArea into your CSS. By utilizing JS, all SVG paths have been targeted and provided with eventListeners.

Due to constraints with length, I am unable to present the entire code here. Therefore, the CSS is outlined as follows:

#core {
  fill: #ff4f81;
  animation: pulse1 1.5s ease-in-out infinite;
}

#radar {
  fill: #F99EAD;
  animation: pulse2 1.5s ease-in-out infinite;
}

@keyframes pulse1 {
  0% {
    opacity: 0;
    transform: scale(0);
  }

  30% {
    opacity: 1;
    transform: scale(1.5);
  }

  60% {
    opacity: 1;
    transform: scale(2);
  }

  100% {
    opacity: 0;
    transform: scale(2);
  }
}

@keyframes pulse2 {
  0% {
    transform: scale(1, 1);
    opacity: 0;
  }

  50% {
    opacity: 1;
  }

  100% {
    transform: scale(6, 6);
    opacity: 0;
  }
}


.selectedArea {
  stroke: black;
  fill: purple;
}

JavaScript:

let selectedArea = null
let areas = document.querySelectorAll("path")
areas.forEach((area) => {
  area.addEventListener("mouseover", function() {
    area.style.fill = "red"
  });
  area.addEventListener("mouseout", function() {
    area.style.fill = ""
  });
  area.addEventListener("click", function() {
    console.log(selectedArea)
    if (selectedArea) {
      document.querySelector(`#${selectedArea}`).classList = "st0"
    }
    if (selectedArea !== area.id) {
      selectedArea = area.id
      area.classList = "selectedArea"
    }
  })
})

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

What is the best method to retrieve text from a <span> element within an <li> element nested inside a <ul> using BeautifulSoup?

I need help extracting the content from the Here’s what’s new section on this page. Specifically, I am trying to capture everything between In the coming weeks and general enhancements. After inspecting the code, I noticed that the <span> elemen ...

Retrieving the selected value from a dropdown menu before it is altered using vanilla JavaScript

I am trying to implement a feature where the previous value of a dropdown is captured when it is changed. Essentially, I need to compare the previous and current values of the dropdown and perform an action based on that information. For example, if Option ...

Running a <script> tag with an external src attribute in a dynamic manner through the use of eval

Currently, I am utilizing the Genius API to fetch lyrics for a particular song and then embed them within an HTML <div> tag. My interaction with this API is through PHP, employing an AJAX GET request. Upon a successful AJAX request, the following HT ...

"Learn how to pass around shared state among reducers in React using hooks, all without the need for Redux

I've built a React hooks application in TypeScript that utilizes multiple reducers and the context API. My goal is to maintain a single error state across all reducers which can be managed through the errorReducer. The issue arises when I try to upd ...

What are some tactics for avoiding movement in the presence of a border setting?

I created a webpage that has the following structure: .topbar-container { width: 100%; position: fixed; top: 0; background-color: #2d3e50; z-index: 999; display: flex; transition: height 500ms; } @media (min-width: 992px) { .topbar-cont ...

Unveiling the method of retrieving a targeted value from JWT in React

I'm struggling to retrieve a specific value from my JWT token in React. I am using the react-jwt library to decode the token, and when I log it, I receive this output: Object { userId: "850dff98-54fb-4059-9e95-e44f5c30be0f", iat: 1698866016 ...

What is the best way to implement a sub-menu using jQuery?

After successfully implementing a hover effect on my menu item using CSS, I am now struggling to make the sub-menu appear below the menu item upon hovering. Despite my efforts to search for jQuery solutions online, I have not been successful. Are there a ...

Tips for identifying when a div reaches the top or bottom of the browser window in Angular 4

This question has solutions available for JQuery (which I prefer not to use in the current project) and Angular1 (which I am unfamiliar with). ...

Difficulty Uploading Files

I'm facing an issue when trying to upload multiple files. When I select more than 1 djz_file, no information is obtained from $_POST and $_FILES. However, if it's a single file, everything works as expected. <fieldset> ...

Issue with Resolving Generic Types into Union

The code snippet below is causing errors: class Base { } class Child1 extends Base { child1Fn() {} static deserialize(bytes: Uint8Array): Child1 { return new Child1(); } } class Child2 extends Base { child2Fn() {} static deserialize(bytes ...

Calculator for calculating values using JavaScript data attributes

One issue is that certain elements are canceling each other out.. The value of the element is specified in the "data-price" attribute. My code is currently not valid and does not handle it properly, ideally I would like to update the total whenever a selec ...

Tips for avoiding cropped images on mobile websites:

I recently created a website that looks perfect on desktop but appears cropped on mobile devices. The site in question is doc.awsri.com Here are the images causing the issue: https://i.stack.imgur.com/eRJXU.png The problem arises when viewing it on a ph ...

Tips for keeping my background image from shrinking when I resize the window?

When I resize the webpage window, my background image shrinks in size. Currently, it is not repeating (which is a step forward), but now I need it to cover the entire screen to avoid showing white space around the background when the window gets smaller. ...

Troubleshooting Django: Issue with template extension causing static image not to be found in child template

For my personal project, I decided to learn Django. Initially, I created two separate apps, "API" and "Search". As development progressed, I merged the search functionality into the API app and updated the views accordingly. I also designed a base template ...

Is it possible to transform the Bootstrap5 sidebar, currently positioned above the block content, into a sticky element on

After creating a Django blog using bootstrap5 and following guidance from the python crash-course book, I encountered an issue with my sidebar placement. Despite trying various methods, I struggled to "override" my blocks in order to keep my sidebar fixed ...

Verify login availability using Javascript auto-check

For quite some time now, I've been grappling with a significant issue that has been consuming my attention. I am determined to implement an auto-check login availability feature in the registration form of my website. My goal is for it to verify the ...

The Java value is not returned by the Observable<boolean> stream

I'm currently working on making a request to the backend for a boolean value using observables, but I'm struggling to figure out the best approach between .map and .subscribe. return this.http.put({url}, credentials, this.requestOptions) .ca ...

Encountering a 404 error for core.js and browser.js while loading an Angular 2 app through system.src.js

I am new to Angular2 and have followed the Angular2 quickstart and tutorial to get started. Just to provide some context, when a user clicks on a link in the top navigation bar of my webapp, it triggers a server side request. The resulting page returned t ...

Is there a way to automate downloading a file in Angular using the browser's built-in download feature?

When I make a request to my webservice to download a zip file, the file content is downloaded secretly and suddenly appears in the download task bar as already fully downloaded (100%). I am using the following method in Angular: const endpoint = "http:// ...

How can you obtain the user ID by verifying an email when using applyActionCode in Firebase 9 modular?

Is there a way to access the UID of an email verified user? Will the response provide any helpful insights, or should I handle this from another source? const handleVerifyEmail = (auth: any, actionCode: any) => { applyActionCode(auth, actionCode! ...