When enclosing my Javascript code in CDATA tags within my SVG files, it does not execute

Having an SVG file in this format:

<svg id="test" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" viewBox="0 0 1435 1084">
<style type="text/css">
    svg{background:red}
</style>
<script type="text/javascript">//<![CDATA[
    const x=1;
    const y=1;

    if (x===y){
        document.getElementById('test').append('<style type="text/css">svg{background:blue}</style>');
    }else{}
//]]></script>
</svg>

The objective is to prevent a specific script from running when the SVG is utilized as an image object, while allowing it to function normally when embedded as an object or within an iFrame, or viewed independently in a browser. The portion of code that should be disabled when used as an image contains a <style> tag.

Although the CDATA tag seemed like a suitable solution for this issue, it did not yield the desired outcome.

This has led to some confusion. I have examined SVGs with CDATA tags that executed correctly, yet when attempting the same approach, the JavaScript does not execute.

Additionally, I am interested in any suggestions for creating an SVG that can trigger different JavaScript depending on whether it's viewed alone, inline, as an object, within an iFrame, or as an image.

I have experimented with various approaches and have identified the CDATA tag as the most promising solution.

Edit: A code snippet has been included. In theory, the SVG background should appear blue in this instance, but it renders as red.

<svg id="test" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" viewBox="0 0 1435 1084">
<style type="text/css">
    svg{background:red}
</style>
<script type="text/javascript">//<![CDATA[
    const x=1;
    const y=1;

    if (x===y){
        document.getElementById('test').append('<style type="text/css">svg{background:blue} </ style>');
} else { }
 // ]]> </script> 
</svg> 

 

Answer №1

It seems like the issue with your script arises from jQuery not being accessible in the environment where you are attempting to execute it.

If jQuery is not available, this particular line will trigger an error:

$('svg').append('<style type="text/css">svg{background:blue}

However, if jQuery is present, your example will function as expected without any alterations needed:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<?xml version="1.0" encoding="utf-8"?>
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" viewBox="0 0 1435 1084">
<style type="text/css">
    svg{background:red}
</style>
<script type="text/javascript">//<![CDATA[
    const x=1;
    const y=1;

    if (x===y){
        $('svg').append('<style type="text/css">svg{background:blue}</style>');
    }else{}
//]]></script>
</svg>

No worries if jQuery isn't at your disposal for this task. Achieving the same effect can be done through native browser APIs:

<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" viewBox="0 0 1435 1084">
<style type="text/css">
    svg{background:red}
</style>
<script type="text/javascript">//<![CDATA[
    const x=1;
    const y=1;

    if (x===y){
        const style = document.createElement('style');
        style.innerText = "svg{background:blue}";
        document.querySelector('svg').append(style);
    }else{}
//]]></script>
</svg>

Answer №2

Scripts inside img elements will not be executed by the browser. Blocking the code is unnecessary.

The append() method is part of DOM Level 3, but its functionality differs from the jQuery method. When using string arguments, they will be appended as text nodes and not parsed.

To create and append the element node, it must be in the SVG namespace.

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1435 1084">
  <style type="text/css">
    svg{background:red;}
  </style>
  <script type="text/javascript">//<![CDATA[
    const style = document.documentElement.appendChild(
      document.createElementNS('http://www.w3.org/2000/svg', 'style')
    );
    style.setAttribute( 'type', 'text/css');
    style.append('svg{background:blue !important;}');
  //]]></script>
</svg>

If simply applying different styles, adding a class to the svg element would suffice.

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1435 1084">
  <style type="text/css">
    svg{background:red;}
    svg.Active {background:blue;}
  </style>
  <script type="text/javascript">//<![CDATA[
    document.documentElement.classList.add('Active');
  //]]></script>
</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

React does not auto-populate form data

I am working on a simple project using Next.js with a basic form. However, when I try to submit the form and log the form data in the console, it shows up as an empty object. I'm puzzled by this issue. Here is my code: import styles from &apos ...

Adjusting the size and location of the current browser window using jQuery

Is there a way to modify the height, width, and position of the browser window using jQuery's document.ready() function? ...

When attempting to call a Firebase Cloud Function URL in an AngularJS $http request, an Access Control Origin Error

I recently created a cloud function that involves linking with Plaid. I'm currently working on calling this function using AngularJS's $http method. While the cloud function code is being executed, I encountered an error in my console instead of ...

Newbie struggling with executing JavaScript in Visual Studio Code

Hey there! I'm new to coding and have been struggling for the past couple of hours trying to get a simple JavaScript code to run on VSC. Can anyone lend a hand in helping me set up my sandbox correctly? Here's a snapshot for reference: https://i ...

What is the best way to transform an array of string values into an array of objects?

I currently have an array of strings with date and price information: const array = [ "date: 1679534340367, price: 27348.6178237571831766", "date: 1679534340367, price: 27348.6178237571831766", "date: 16795 ...

Check the File Format (not just the Extension) prior to Uploading

When uploading a file within an HTML form, you can validate the extension using JQuery's Validation plugin: <form enctype="multipart/form-data" id="form-id"> <input type="file" name="file-id" id="file-id" /> </form> To validate ...

What could be causing me to receive 'undefined' and an empty array[] when using Promise.all with JavaScript async operations making calls to Azure APIs?

In my personal project utilizing Azure AI APIs and Node.js/Express,, I am working on handling a get request to a /viewText route by extracting text and key phrases from an uploaded image/document. Below is the code snippet that should log this data to the ...

Node.js and Express: tackling the problem of duplicate variables

I have a checkUser middleware that saves the user information when a JWT is verified. However, when I integrate it into my routes and attempt to log res.locals.user.username, the username appears twice in the console. This duplication is causing issues wit ...

Exploring ways to create a dynamic background image that allows the rest of the page to float over seamlessly

Currently working on a responsive website and almost done with the build. However, I came across a site where an image appears to be floating behind the rest of the webpage content. Tried searching for a solution using w3.css without any luck. Any sugge ...

An artistic arrangement of images seamlessly fitting together in a rectangular shape using HTML and CSS

I am currently working on creating a collage of images that need to fit perfectly within a rectangle. I have successfully completed the top layer, but I am facing some confusion with arranging the images in the last row using CSS. (For better visualization ...

Node for Angular forms workflow

I'm on the hunt for workflow nodes with forms that open when the user clicks on them. While I've come across a few options, not all of them are open source. Can you point me towards some open source (simple and basic) alternatives? Here's w ...

The C# MVC Controller is having difficulty retrieving decimal or double values from an Ajax POST request

Having trouble sending decimal or double values via ajax to my C# MVC Controller. The values always come through as null, even though they work fine when sent as strings or integers. Why is this happening? When checking the client's request, the corre ...

Tips for sending multiple variables to PHP using jQuery

Hello everyone, I could really use some assistance with a jQuery and AJAX issue I'm facing. I admit that I am not very well-versed in these technologies, so it's likely that I am missing something simple here. My problem lies in trying to pass mo ...

JavaScript Newbies Encounter OnFocus Dilemma

How can I add default grey text to a text field on an ASP.net page, and make it disappear when the user clicks or enters the field? I have successfully implemented onFocus event for changing text color in my .aspx page using a <script> tag with JS c ...

Adapt a dynamic nested flexbox grid into a stacked layout optimized for mobile devices

Utilizing the power of the CSS3 Flexible Box layout has been crucial in developing a responsive site that caters to various devices. On desktop screens, I have successfully implemented a flexbox layout that looks like this: body { text-align: center; ...

Navigate to a URL when App.js mounts using componentDidMount

Currently, I am working on a feature that requires a user to complete their profile upon logging into the app. If a user logs in and has not completed their profile, they should be redirected to a specific URL whenever they try to navigate to any page (exc ...

Discuss the significance of using require('.') in a Node.js environment

During my exploration of a node.js CLI module documentation, I came across a peculiar line. It involved including external modules in a specific way - using the '.' symbol during the process. While I am familiar with how to include external modul ...

What is the best way to position my logo on top of the stunning space background?

Click here to check out the code on CodePen Please take a look at my code on codepen.io. I am new to Stack Overflow so please be patient with me if I make any mistakes. ;-; I currently have my logo (https://i.stack.imgur.com/W0nWc.png) included in the co ...

Restrict Recursive GraphQL Schema Query Depth with graphql-sequelize resolver in Node.js using express-graphql

In my code, I have two models called User and Post. My goal is to retrieve User information when querying a post, as well as obtain all of a User's posts when querying a user. These two models are associated in the following manner: User.hasMany(Pos ...

Adjust the position of the footer up or down based on changes in page content height

If I have jQuery at my disposal, how can I achieve the following task? There is a div on the page with dynamic content and no fixed height. The height of this div changes as users type and content appears or disappears accordingly. Although everything is ...