controlling elements outside of an SVG using JavaScript functions embedded within the SVG

On my website, I am adding an svg-graphic and hoping to control other parts of the site using javascript commands that are within the svg itself. However, I am uncertain if this is achievable.

Here's the scenario: I have a world map in svg format, and I want users to be able to click on a country to trigger an ajax call that will load relevant information about that country into a div on the html page where the svg is embedded.

Currently, using "onclick="location.href='xxx'"" takes users to the respective site, but I would rather run a js function to fetch the site via ajax. The issue is that running a javascript function within the svg only seems to affect elements defined within the svg, not those outside of it.

Is it possible to manipulate elements outside of the svg through a javascript function within the svg? If so, how can this be achieved?

Best regards, Christian

Answer №1

An interesting aspect to note is that the SVG element is actually a child of the "window", rather than being a direct child of the "window.document" as is typical. This means that if you have a script within the SVG, you will need to access elements in your document using

this.parent.document.getElementById("theIDYouWant")

On the other hand, if you have a script in the <head> or <body> section of your document, you can access elements within the SVG by following a pattern like this:

window.theIDofYourSVG.childNodes[theNumberOfTheThingInYourSVG]

Answer №2

Implement a click event for the svg-object by adding an onclick attribute that calls the replaceLink function with 'yourdata' as the parameter. Define the replaceLink function within the svg element like so:

function replaceLink(data)
    {
        parent.replaceLinkinHTML(data);
    };

In the HTML where the svg is embedded, add a replaceLinkinHTML function to easily manipulate the html-page from the svg...

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

Transform the array of strings

I'm currently working with an array that looks like this: ["[Date.UTC(2016,09,30),250500.00]","[Date.UTC(2016,09,29),255100.83]", "[Date.UTC(2016,09,28),255600.82]"] What would be the best way to transform it into a structure like this? [[Date.UTC( ...

Tips for showcasing a Bootstrap alert

I'm attempting to integrate Bootstrap Alerts into my project, but I'm struggling to display them programmatically. Here is the HTML snippet: <div class="alert alert-success alert-dismissible fade show" role="alert" id="accepted-meal-al ...

Displaying all items in a collection as HTML using Node.js

I am looking to showcase all the items in my mongodb collection as HTML. In the past, I have accomplished this with simpler tasks, such as... router.get('/', function (req, res) { res.render('home', { title: 'Express', u ...

Choose2 generateUniqueEntry identification from submission

I am currently using select2 for a tagging input, but I am facing some challenges when it comes to handling the creation of new tags and retrieving the new tag IDs back into the select2. This issue is closely tied to another question on this topic which c ...

Is there a way to prevent certain folders that have .vue files from being included in the VueJS build process?

https://i.sstatic.net/YU1rB.png module.exports = { presets: [ '@vue/app' ], module:{ rules: [ { test: /\.vue$/, exclude: [ './src/components/Homepages/number1', './src ...

The passing of the AJAX and $_POST field did not occur

Hey there! Can you provide a quick tip on what might be wrong in this scenario? I'm trying to send $_POST['url'] to a PHP file using AJAX. AJAX: <script> $('#checkUrl').click(function() { $('#loader').css("di ...

What is the best way to apply a mask to a textbox to format the date as MM/yyyy using a mask

In my asp.net application, I have a TextBox for entering Credit card date (month & year only). I tried using the 'TextBox with masked edit extender' and set Mask="99/9999" with Mask Type="Date. However, it is not working as expected - it only wor ...

Error: The function $scope.apply is invalid and cannot be executed

I am attempting to display the contacts list after retrieving it using rdflib.js. The data is being loaded and stored in the list within the scope. However, I am running into an issue where the $scope is not updating, and it appears that I may be calling ...

The div height adjustment peculiarities in IE7 and IE8 are causing quite a stir

I recently encountered a problem with my HTML/JS code that I thought was simple. The code is designed to expand the size of a div on mouseover and then collapse it back on mouseout. Here's how the code looks: CSS: .sign-in-up { position: absolut ...

JavaScript is failing to update the table values as users interact with it

I've created an HTML table and used PHP to populate the values. The goal is to allow users to update order statuses with a status and message input. Initially it works fine, but after multiple uses, it either updates the wrong row or doesn't up ...

Utilize regular expressions on a JSON response dataset

Imagine a scenario where a client makes a GET request and the response is in JSON format similar to the following: var result = { "enabled": true, "state": "schedule", "schedules": [ { "rule": { "start": "2014-06-2 ...

Objects may unexpectedly be sorted when using JavaScript or Node.js

When I execute the following code using node app.js 'use strict'; var data = {"456":"First","789":"Second","123":"Third"}; console.log(data); I am receiving the following output: { '123': 'Third', '456': 'F ...

Complete a submission using an anchor (<a>) tag containing a specified value in ASP.Net MVC by utilizing Html.BeginForm

I am currently using Html.BeginFrom to generate a form tag and submit a request for external login providers. The HttpPost action in Account Controller // // POST: /Account/ExternalLogin [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public Acti ...

What is the correct way to show a JavaScript response on the screen?

Here is the JavaScript code I used to call the server API: <script type='text/javascript'> call_juvlon_api(apikey, 'getAvailableCredits', '', function(response) { document.getElementById('show').innerHT ...

When the datatype is specified, $.post fails to function

I have encountered an issue with the following code. When I remove , "json"); from the end, it seems to work but only results in a failure. Despite referring to the jQuery specs on their website, I am unable to identify why the $.post method is not functio ...

Using JSON.stringify() for custom serialization of an object

Imagine there is an object called a with properties: const a = { foo: 123, bar: 'example' } Now, this object is a part of another object called b like this: const b = { a: a, anotherField: "example" } While working with TypeScript, th ...

What is the most efficient way to extract a key and its corresponding value from an object containing only one pair?

Currently, I am developing a recipeBox application using React JS. Within this application, there is a state defined as: this.state = { recipeArray: [] ...} Users have the ability to add recipes by pushing objects {recipe_Name : Ingredients} into tha ...

Creating an HTML design with divs: a trio of pictures that adjusts in size to match the viewport (sl

As a newcomer to HTML and CSS, I find myself nearing completion of my website, with the final obstacle being an image slider in the background. The Challenge: The images are not perfectly centered within the viewport. Specifically, the first image needs ...

Transferring parameters via URL - When passing single quotes, they are converted to &#39;

In my current ASP.NET project, we encounter an issue with passing parameters through the URL. Whenever a single quote is passed, the URL automatically changes all single quotes to %27 and the actual JavaScript value reads them as &#39; I need assistan ...

Create seamless communication between Angular application and React build

I am currently engaged in a project that involves integrating a React widget into an Angular application. The component I'm working on functions as a chatbot. Here is the App.tsx file (written in TypeScript) which serves as the entry point for the Rea ...