Is there a way to attach event listeners to raw HTML that has been imported using code?

I'm facing a challenge with importing SVG code embedded in an HTML file and using the v-html directive to render it. The issue is that I need to attach click events to the anchor tags within that imported file, which are not part of my main template.

  • Is there a way to retrieve all the anchor tags from the imported file?

  • And how can I bind events to these elements without relying on the v-on directive?

The template structure:

            <v-flex mt-2 px-0 xs6 
                    ref="map_svg"
                    v-html="mapHTML">
            </v-flex>

Excerpt from the imported file:

<svg>
  <g>
     <g>
        <a target="_blank" xlink:href="url to a subsite" >
            <!-- content path which shows a circle -->
         </a>
     </g>
     <g>
        <a target="_blank" xlink:href="url to a differnt subsite" >
            <!-- content path which shows a circle -->
         </a>
     </g>

     <!-- additional similar elements as shown above -->
  </g>
</svg>

I want to add a click event to these anchor tags and either remove or change the xlink:href attribute so that they don't open new tabs in the browser upon clicking.

Edit

This was the solution I implemented:

  mounted() {

    const that = this;
    const links = this.$el.querySelectorAll('#map_svg svg > g > g > a');

    links.forEach(el => {
      const url = el.getAttribute('xlink:href');
      if (url) {
        // el.addEventListener('click', that.stationClick(url));
        el.onclick = function (){
          that.stationClick(url);
        }
        el.removeAttribute('xlink:href');
      }
      el.removeAttribute('target');
    });
  },

Answer №1

Once your SVG has been properly loaded, you can set up click event listeners on the elements within it:

export default {
  name: "App",
  data() {
    return {
      svgContent: null
    };
  },
  methods: {
    async loadSvg() {
      // Load your SVG content here
      this.svgContent = `
        <a href="https://example.com" target="_blank">Example Link</a> 
      `;

      // Use $nextTick to wait for DOM refresh before binding events
      this.$nextTick(() => { 
        this.bindClickEvents() // Bind click events after SVG is loaded
      })

    },
    bindClickEvents () {
      // Find all anchor tags within the SVG container
      this.$refs.svg_container.querySelectorAll('a').forEach(element => {
        element.removeAttribute('target') // Remove any existing 'target' attribute
        element.addEventListener('click', this.handleClick) // Set up click event listener
      })
    },
    handleClick (event) {
      // Handle the click event as needed
      event.preventDefault()
    }
  }
};

Answer №2

Utilize the ref that has been established and regular JS to connect with the tags.

this.$refs.map_svg.querySelectorAll('a').forEach(element => element.addEventListener('click', this.callback) )

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

``There seems to be a malfunction with the modal feature in the asp.net

Within my strongly typed view, I have a loop that iterates over a list of objects fetched from a database. Each object is displayed within a jumbotron element, accompanied by a button labeled "Had role before". When this button is clicked, a modal opens wh ...

Selecting options using AngularJS to parse through a list

I am faced with a challenge involving a collection of strings representing years. Here is an example: $scope.years = ["2001", "2002", "2003", ...]; My goal is to display these values in a select tag within a web page. However, whenever I attempt this usi ...

Error encountered when trying to generate a collection from JSON using Backbone framework

jQuery(function() { var Hotel = Backbone.Model.extend({ defaults: { idHotel:"", hotelName:"Grand Marina", hotelAddress:"Lakeview Drive", hotelStars:"4", hotelRoomsCount:"180", ...

casperjs is encountering difficulty locating the id even after setting it

Issue with CasperJS not locating the ID after setting it Casper.then(function () { screenLog(); var id = String("_newid_"); var arrow = this.evaluate(function () { var arrows = document.querySelectorAll('span.select2-selection__a ...

What is preventing the fetch from functioning properly within the nuxtServerInit of the store?

With my current project setup using Nuxt, I encountered an issue within the store's action code snippet: async nuxtServerInit({ commit }) { this.dispatch('fetchAllClients') }, async fetchAllClients({ commit, state }) { console.log(' ...

Validate if the Jquery AJAX response contains any data

I've been attempting to integrate an alert message in my code that triggers if the response is null, but every time I try to do so, something goes wrong. If anyone has any suggestions or assistance with this issue, it would be greatly appreciated. He ...

Error with Cross-Origin Resource Sharing (CORS) on my website

During the development of a website, I disabled web security in order to bypass CORS using the command chrome.exe --disable-web-security --user-data-dir=/path/to/foo However, after successfully completing the website and uploading it to my domain, I enco ...

Adding a static global constant in webpack dynamically

I'm facing a challenge with adding a global constant to my project using webpack.DefinePlugin. I've successfully added one in the module.exports, but I struggle to do this conditionally. When I declare and use '__VERSION__' in my module ...

When using the setTimeout function to update the state, React useContext appears to be ineffective

As a newcomer to React, I have a question about refreshing the score in my card game within a forEach loop using setTimeout. While the state appears to update correctly, the DOM (Component overarching) does not reflect these changes. export function Refill ...

How to prompt the browser to download a file with a specific name using node.js and express

I've created a node/express website as part of my university project. It allows users to search for a specific law ID, which then displays a table with various files in different formats and languages related to that ID. I am using the "http-proxy" mo ...

Utilize three.js within a Google web app script - unable to incorporate the script module type for loading three.js

Looking to incorporate three.js into a Google Web Script to load 3D CAD files, I discovered that the installation instructions on threejs.org specify the script needs to be of "module" type. However, after researching for several days, it seems that Google ...

Implement a click event for the newly added item

I am struggling to attach a click event to an element that I dynamically added using jQuery. When the item is present in my HTML code, everything works as expected. Please refer to the code below for clarification: HTML <div id="addNew">Add new Ite ...

What causes a Next.js App to crash when a prop is not defined in destructuring code?

Let me share the issue I am facing. I have developed a custom Context API wrapper to handle all my data. However, there is this docType property that may not always be defined or may not exist at times. When I destructure it in this way: const { docType } ...

The feature of determining if an edge exists, within the dagre-d3/graphlib,

Has anyone utilized the graph.hasEdge function in dagre-d3/graphlib to check for the existence of an edge between two nodes? This API takes two arguments representing the two nodes and verifies if there is an edge connecting them. I am facing an issue whe ...

Click on the login button once the field has reached its maximum length

I need assistance with a login form that has a maximum length of 4 characters for both empNum and ssn. Below is the code snippet: <input type="text" id="empNo" name="empNo" style="width: 90px; margin-left: 10px" maxlength="4" onkeyup="nextField(this, & ...

Angular parent scope does not reflect changes when a directive updates the shared scope variable

My directive is designed to validate and modify a specific binded value before triggering the button action. However, I am facing an issue where any updates made to the directive value are not being reflected in the parent scope. Even though I have used (= ...

What is the best way to add a "Save to Favorites" link within a modal window

I have integrated the NASA API to showcase images, where clicking on an image reveals a modal containing additional details. There is also a save to favorites functionality in the tutorial that allows users to save images and details to a local storage sec ...

What is the best way to utilize AJAX in sending chosen files to a PHP script?

I currently have two forms set up. Form A includes fields for name, age, address, email, and a hidden text field that holds the names of images to be uploaded in form B. Form B allows users to browse and select their photos using an input type File. ...

Vue 3 has officially deprecated the use of ::v-deep as a combinator. Going forward, please utilize ::v-deep(<inner-selector>) instead

Recently, an error message has been popping up in Vue 3 regarding the use of ::v-deep. The warning states that using ::v-deep as a combinator is deprecated. Instead, it recommends using ::v-deep(<inner-selector>) Here is an example of the CSS ...

Error 400 encountered when attempting to send anti-forgery token through axios.post request

I have a ApiController that has the attribute [ValidateAntiForgeryToken] To add Antiforgery to my razor form, I included the following: <form action="" class="default-form" ...