Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery with an SVG document

jQuery is designed to be used in HTML pages with JavaScript.

SVG uses the same DOM Level 2 as HTML but is XML-based and specifies ECMAScript.

What problems could result from using jQuery with SVG? Would it be preferable to embed such SVG as an element in an HTML document?

Note, I'm not referring to the "jQuery SVG" drawing library which provides for manipulation of an SVG element in an HTML document as a graphics port using jQuery syntax. What I want is to use jQuery selectors and event management on SVG elements, with the SVG root maybe being inside HTML or maybe not.

like image 771
Potatoswatter Avatar asked Dec 19 '12 06:12

Potatoswatter


People also ask

Does jQuery work on SVG?

SVG uses elements in the DOM ie. Accessing it and manipulating it can be done the same way jQuery manipulates any other Object in the DOM. ie. $('svg path').

Can SVG integrate with JavaScript?

Like HTML, SVGs are represented using the Document Object Model (DOM) and so can be manipulated with Javascript relatively easily, especially if you are familiar with using JS with HTML. All the code examples can be found by following the Github link at the top of this post.

How do I input SVG into HTML?

SVG images can be written directly into the HTML document using the <svg> </svg> tag. To do this, open the SVG image in VS code or your preferred IDE, copy the code, and paste it inside the <body> element in your HTML document. If you did everything correctly, your webpage should look exactly like the demo below.

Can I use SVG in react native?

react-native-svg provides SVG support to your React Native project on both Android and iOS platforms. react-native-svg-transformer enables you to import local SVG files in your React Native project, like how you would do in a Creact React App project on the web.


1 Answers

Trying it out, selectors seem to work but other things don't. The $( function() { } ) idiom to initialize the page doesn't work because SVG only passes an SVGLoad event to the top <svg> element. $('svg').bind('SVGLoad', function(){}) does work, though.

Dynamically adding elements with .append puts them in the DOM such that they don't get rendered, at least on Firefox. The phantom elements remain invisible even after the document is re-rendered including an element dynamically added without jQuery. $().attr(key, value) may change an attribute but not update the onscreen display.

It all seems unfortunately broken. More features work once it's embedded in an XHTML document. But defects such as the above remain and it's probably better to use another framework. Maybe give jQuery SVG another look…

like image 161
Potatoswatter Avatar answered Oct 17 '22 15:10

Potatoswatter