SVG images suddenly disappearing in Chrome following a javascript script execution

My webpage has a sticky footer, but I am experiencing issues with SVG files not displaying in Chrome when the javascript for color changing on hover is enabled. Interestingly, disabling the javascript allows the images to load properly in Chrome.

I have tried to reproduce the problem in a jsfiddle without success, but here is the code: https://jsfiddle.net/r9szd060/

This is the javascript code snippet causing the issue:

$( document ).ready( function () {
    $( 'img[src$=".svg"]' ).each( function () {
        var $img = jQuery( this );
        var imgURL = $img.attr( 'src' );
        var attributes = $img.prop( "attributes" );

        $.get( imgURL, function ( data ) {
            // Get the SVG tag, ignore the rest
            var $svg = jQuery( data ).find( 'svg' );

            // Remove any invalid XML tags
            $svg = $svg.removeAttr( 'xmlns:a' );

            // Loop through IMG attributes and apply on SVG
            $.each( attributes, function () {
                $svg.attr( this.name, this.value );
            } );

            // Replace IMG with SVG
            $img.replaceWith( $svg );
        }, 'xml' );
    } );
} );

Despite trying to use the embed tag instead of the img tag, the behavior remains unchanged in chrome. Although Firefox (desktop + iOS + Android) and Safari (desktop + iOS) display the SVG images correctly, they disappear in Chrome on desktop and android. Surprisingly, chrome on iOS seems to work fine...

I suspect it may be related to how Chrome handles SVGs using JavaScript and how the SVG file itself is formatted, but my knowledge of javascript is limited. I have heard about potential issues with SVG files in Chrome, but I'm unsure how to provide the relevant information from the SVG file (e.g., opened in illustrator) to troubleshoot further. If anyone can offer insights on how to resolve this issue, I would greatly appreciate it!

Can anyone help identify the problem and suggest a solution?

Answer №1

To apply styles to an SVG using CSS, you need to set attributes on the SVG element itself, specifically for setting the width. This is why SVG images do not appear styled on the page initially, as each SVG retains its original size (usually around 600px).

$( document ).ready( function () {
    $( 'img[src$=".svg"]' ).each( function () {
        var $img = jQuery( this );
        var imgURL = $img.attr( 'src' );
        var attributes = $img.prop( "attributes" );

        $.get( imgURL, function ( data ) {
            // Extract the SVG tag from the data
            var $svg = jQuery( data ).find( 'svg' );

            // Remove any invalid XML tags
            $svg = $svg.removeAttr( 'xmlns:a' );

            // Transfer IMG attributes to the SVG element
            $.each( attributes, function () {
                $svg.attr( this.name, this.value );
            } );

            // Set a specific width on the SVG element
            $svg.attr('width', '30'); 

            // Replace IMG with the updated SVG element
            $img.replaceWith( $svg );
        }, 'xml' );
    } );
} );

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

Using jQuery along with PHP to handle request and response functionalities

I'm unsure of what exactly to search for, but I need a solution. The task at hand involves extracting text with ID's (#ftext_1,..._2,..._3,..._4) from an HTML file and sending them to a PHP file. Once manipulated in the PHP file, they must be in ...

How to choose the second anchor element in a list with Protractor

I am facing a challenge where I need to click on the 2nd anchor tag in a list of anchor tags. <ul id="shortcuts"> <li><a ui-sref="app.journeyExplorer" href="#/journey-explorer/"><span class="ng-binding">1</span></a> ...

Looking for assistance with regards to submitting an event

I have been working on developing a form and validating it using jQuery before submitting it to the server. Everything seems to be functioning correctly except for the function on the submit event. The form is being submitted with errors and upon checking ...

Error Uploading File - Functioning in Postman but not on website interface

I'm currently pursuing the full stack certification on devchallenges.io and tackling the authentication app challenge. So far, I've successfully implemented the login and register functionality, as well as fetching the logged-in user's infor ...

The table is too wide for its parent mat-nav-list, stretching to 100%

Here is the code snippet I am using to display a table inside a mat-nav-list: <mat-nav-list> <table> <tr>Node Information</tr> <tr> <td>Name</td> <td *ngIf="activeNod ...

Run JavaScript code whenever the table is modified

I have a dynamic table that loads data asynchronously, and I am looking for a way to trigger a function every time the content of the table changes - whether it's new data being added or modifications to existing data. Is there a method to achieve th ...

Packages and Digital Routes

Currently in the process of creating a new website utilizing angular, MVC, and Web API. The plan is to keep the static content (js, css, images, etc) in Site A, the MVC site in Site B, and the api in Site C. These will be separate sites, not virtual direct ...

Tips for updating the value of the most recently created div in an ng-repeat loop

Within my HTML document, the following code is present: <div ng-repeat="selection in selections" style="margin-left:{{marginLeft}}%;width:{{progress}}%;background-color:{{selection}}"> </div> In my controller, I have implemented function ...

Finding the date of a month prior based on a fixed initial date - here's how!

I have a specific requirement to display a subscription date range on a webpage in the following format: 31 May 2023 — 30 June 2023 When a user subscribes, the backend sends a fixed subscription start date that remains constant. For example, if a user ...

React-Tooltip trimming

Currently, I am facing a dilemma that requires some resolution. The issue at hand is related to the placement of React-Tooltip within the List element. Whenever it's positioned there, it gets clipped. On the other hand, placing it at the bottom isn&a ...

Slide a floating container downward by one line

I am in search of a way to create a unique text effect resembling a "sidebox" within my writing. The goal is to have a note or heading positioned at the start of a paragraph, floating either to the left or right with some negative space surrounding it and ...

Steps to trigger a dialog to appear automatically within an Icon Menu with React Material UI

In my application, I have an icon menu implemented along with an array that contains the possible values for the items in the menu. Here is an example of how the array looks: listItems = { [ { label: 'ZERO', t ...

Unable to view error messages displayed on the screen during jQuery validation

I seem to be having trouble and can't figure out what I'm doing wrong. When I click on submit, no error messages are displayed. Below is the code snippet: <%@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html"%> < ...

Tips for receiving a positive outcome following the scanning of a login QR code through the baileys API

After successfully integrating the Baileys Rest API from this Baileys-Rest into a Laravel Inertia project, everything seems to be working fine. However, the challenge now is how to continuously monitor the session status response, especially when a user sc ...

How can you merge the class attribute with the ng-class directive based on boolean values?

In my custom directive's link function, I have the following code that dynamically generates a map using d3... map.append("g") .selectAll("path") .data(topojson.feature(counties, counties.objects.counties).features) .enter() .append("path") .attr("d" ...

Determine the number of occurrences of a specific object property within an array consisting of multiple objects

Currently, I am working on developing a lottery system using JavaScript and React to enhance my skills. One of the challenges I am facing is creating a function that can identify the most common bet combination in my betObject array and then list all the b ...

Inquiry regarding the setTimeout function requiring an answer

I have a question about how setTimeout works. Does it wait for the previous code to finish executing before moving on to execute something else after a set time, or does it simply wait for a specific amount of time and then continue with the rest of the co ...

issue with eval() function

I am attempting to convert a JSON string from my .php file using the eval() function, but it is not working. The browser console shows a SyntaxError: expected expression, got '<'... However, when I comment out the line where eval() is used an ...

What is the method to retrieve values passed to the next() function in Node.js?

For my current project, I am utilizing Node.js in combination with Express.js to develop the back-end. In middleware functions, next() is commonly used to progress through the chain until reaching the final app.VERB() function. My question is, at what poi ...

Integrating Speech-to-Text functionality into a React Native chat application: A step-by-step guide

For our project, my friends and I are developing a chat application that will incorporate Google's Speech-To-Text, Text-to-Speech, and Translation APIs. We have successfully integrated Gifted Chat and Firebase into the app, with Text-to-Speech already ...