Author: Stasyuk Eugene 134 Tags: , 16.12.2022

Graphics in svg format is a fairly convenient and widely used image format. For example, in an svg with css styles, we can change its color. And as we know, we can do this procedure only if there is markup on the svg page. But what if such an image is connected to the page using the img tag. In this case, the following code will come to our aid:

(function($ = jQuery) {
		$('img.svg').each(function() {
			let img = jQuery(this);
			let imgID = img.attr('id');
			let imgClass = img.attr('class');
			let imgURL = img.attr('src');

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

				// Add replaced image's ID to the new SVG
				if (typeof imgID !== 'undefined') {
					svg = svg.attr('id', imgID);
				}
				// Add replaced image's classes to the new SVG
				if (typeof imgClass !== 'undefined') {
					svg = svg.attr('class', imgClass + ' replaced-svg');
				}

				// Remove any invalid XML tags as per http://validator.w3.org
				svg = svg.removeAttr('xmlns:a');

				// Check if the viewport is set, if the viewport is not set the SVG wont't scale.
				if (!svg.attr('viewBox') && svg.attr('height') && svg.attr('width')) {
					svg.attr('viewBox', '0 0 ' + svg.attr('height') + ' ' + svg.attr('width'))
				}

				// Replace image with new SVG
				img.replaceWith(svg);

			}, 'xml');

		});
	})();
  1. We take it and put it in a file with scripts. (Please note that this code will only work if jquery is connected.)
  2. Then, on the page we need, we find the img tag whose image we want to expand and add the “svg” class to it

Other articles

DOMSubtreeModified – event on element change action

DOMSubtreeModified – event on element change

DOMSubtreeModified – event on element change

Brief background I had a website in which the forms were configured on the Contact Form 7 plugin. These forms themselves were integrated with Mailchimp. The challenge was this: after a user fills out and submits a certain form, the message should go to the service with a certain tag (Mailchimp tags are the easiest […]

Popup window on the site (modal window) pop-up window

Popup window on the site (modal window)

Popup window on the site (modal window)

When I was just learning the basics of development, I used to make a popup window manually. Yes, yes – instead of finding some ready-made solution, I did this thankless task 🤪. It seemed to me that there was nothing particularly complicated about it. But, only after some time of working on this issue, I […]