Modifying SVG after it has been loaded - javascript

How would I modify an SVG file after it has been loaded by the browser, preferably through jquery? A simple example would be pressing a button and the color of the SVG element changes. Any documentation would help as well.
EDIT: This link helped a great deal:
w3.org/Graphics/SVG/IG/resources/svgprimer.html#SVG_in_HTML

You can't "modify" SVG files (except by changing them on the server). SVG files define a collection of SVG objects, each of which can be identified with an ID, if you wish. These objects can be manipulated with JavaScript like you would any DOM element (e.g. setAttribute, etc). Check http://www.w3.org/TR/SVG11/types.html#BasicDOMInterfaces for the DOM interfaces. Notice that SVGElement extends Element, which is the basic DOM element type.
EDIT: simple example:
<html>
<body>
<input type="button" onclick="doSVGThing()" value="change">
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<rect id="aRect" x="10" y="10" height="100" width="100"
style="stroke:#ff0000; fill: #9999ff"></rect>
</svg>
<script type="text/javascript">
function doSVGThing() {
var r = document.getElementById('aRect');
r.setAttribute('style', 'stroke: #00ff00; fill: #99ff99');
}
</script>
</body>
</html>

Related

gsap animation - import only one svg or multiple svgs

I would like to do "complex" animation with gsap and svgs.
but I don't know what is the best approach to this.
it is better to create and to import an unique svg with all the elements or maybe it is better 4 different svgs?
I have 4 different characters: a tree, a lamp, a desk and a man.
basically my animation is move the objects on the x, and appearing and to disappearing stuff.
If the elements of the animation are part of one complex animation, you can use one single SVG for this.
To control the DOM of the SVG via CSS and JavaScript you need to add the SVG directly inline into your HTML page. Not embed via img tag or object tag or similar.
<body>
<h1>My SVG Animation</h1>
<svg width="100" height="100" viewBox="0 0 300 100">
<circle class="animation-element-01" cx="50" cy="50" r="40"/>
<rect class="animation-element-01" x="150" y="20" width="150" height="150"/>
<!-- etc -->
</svg>
</body>
Another advantage of this method is, that there is no additional html requests.
Plus the whole animation can be made responsive via the viewBox.

Generated SVG image doesn't display

I'm developing a JavaScript class to show all SVG objects, but when I create the element "image", the browser doesn't display it. Though if I copy the generated code and put it in another document, the image is displayed.
When I searched the image using Firebug's inspector, the object appears but the image is not displayed.
I created the object using appendChild(), setAttribute() and setAttributeNS()
This is the generated code:
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" height="100%" width="100%" >
<image width="50" height="50" xlink:href="logo.png" y="20" x="20" id="d"></image>
</svg>
What I am doing wrong?
The problem were the namespaces. This is the correct form to create images dynamically:
image.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', 'flower.png');
More imformation can be found on MDN's 'Namespaces Crash Course'.

Inline SVG and HTML DOM Scope for .getElementById

The problem space:
I have an SVG map that I embed inline to html using JQUERY Ajax. Then I use java script to address many elements in the svg object to change attributes and add event listeners based on data series. The data and the maps are interactive. Users can change state over many permutations.
I am also using JQUERY UI 1.10.3 Tabs
There are numerous categories. Therefore depending on the presentation there could be multiple copies of the svg map on the same Tab and many different Tabs having the same svg map.
Each copy of the svg document has the same element IDs. The problem I am experiencing is that the element IDs are conflicting with each other in the HTML DOM. So that the only elements that are addressable are the elements from the svg object that occurs first in the HTML document.
My question is:
Do I need to make the elements IDs unique for each instance of the svg object? Or is there a way to set scope and context to the svg object in the HTML DOM?
Example:
Each containing div has a unique ID that I use to insert the svg document and retrieve the SVG document.
<div id="svgMap_div_1" class="cIG" style="height: 500px; width: 750px"></div>
Code used to load the svg document that is received from ajax (mimeType = "image/svg+xml"):
document.getElementById('svgMap_div_1').appendChild(svgXMLObject.documentElement)
Code used to retrieve the svg document. The declaration for svgDoc is local to the function it is implemented in and is unique.
var svgDoc = document.getElementById('svgMap_div_1').ownerDocument;
Code used to update the individual elements. When the identical svg objects (child elements have the same IDs) are in the same HTML DOM, then this javascript will always address the svg object that occurs first in the HTML DOM even if it is retrieved from a discrete div for example id='svgMap_div_2'.
var svgElem = svgDoc.getElementById('elemID');
svgElem.setAttribute("fill", '#0000FF');
I believe that the root of the problem is that svgDoc is retrieved using ownerDocument. Rather than create a discrete object with scope and context, it reaches through to the entire DOM so that the DOM is the context. See the code reference from the IDE:
HTMLDocument Node.ownerDocument
Property ownerDocument http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html
See Also:
Document
Since:
Standard ECMA-262 3rd. Edition
Level 2 Document Object Model Core Definition.
#type
Document
I can develop a working algorithm to make all of the ids unique if I have to but I sure would like to find a better way. I have experimented with other methods and properties to get a working svg document object but none of these are working for me.
Below is a working example to demonstrate what happens when both svg objects are in different div on the same page. All four combinations change the color of the first rectangle. If you change the ID for the rect in the second object to 'box-b' and address it accordingly ('bbox_div', 'box-b'), then both rectangles are operated on independent from one another.
<script type='text/javascript'>
function colorBox(divID, svgElem, colorHex) {
/* DOM This is the original solution that did not work !!!*/
// var svgDoc = document.getElementById(divID).ownerDocument.
// var svgBox = svgDoc.getElementById(svgElem);
// svgBox.setAttribute("fill", colorHex);
/* querySelector */
// document.querySelector("#"+divID + " ."+svgElem).setAttribute("fill", colorHex);
/* jquery div */
// var svgBox = $('#'+divID+' svg').find('#'+svgElem);
// svgBox.css("fill", colorHex);
/* jquery class */
$('#'+divID+' svg').find('.'+svgElem).css("fill", colorHex);
}
</script>
<div style="height: 100px; width: 100px">
Box A Red<br>
Box A Blue<br>
Box B Red<br>
Box B Blue<br -->
</div>
<div id="abox_div" style="height: 100px; width: 100px">
<svg xmlns="http://www.w3.org/2000/svg"
width="0.990919in"
height="0.597218in"
viewBox="0 0 71.3461 42.9997">
<style type="text/css">
<![CDATA[
.allboxes {fill:#00FF00}
]]>
</style>
<g class="box-a allboxes" transform="translate(0.24,-0.24)" fill="#e8eef7">
<rect x="0" y="0.48" width="70.8661" height="42.5197" ><title>Box A</title></rect>
</g>
</svg>
</div>
<div id="bbox_div" style="height: 100px; width: 100px">
<svg xmlns="http://www.w3.org/2000/svg"
width="0.990919in"
height="0.597218in"
viewBox="0 0 71.3461 42.9997">
<g class="box-a allboxes" transform="translate(0.24,-0.24)" fill="#e8eef7">
<rect x="0" y="0.48" width="70.8661" height="42.5197" ><title>Box B</title></rect>
</g>
</svg>
</div>
I believe it's strictly speaking invalid HTML if you have duplicate IDs. I'd suggest using some other mechanism of identifying the elements, either using classes instead of IDs or data- attributes. Then you could move from .getElemntById() to either .querySelector() (try on JS Bin):
<html>
<head>
<title></title>
</head>
<body>
<div id="div1">
<svg xmlns="http://www.w3.org/2000/svg" width="50px" height="50px">
<rect class="rect1" width="50px" height="50px"/>
</svg>
</div>
<div id="div2">
<svg xmlns="http://www.w3.org/2000/svg" width="50px" height="50px">
<rect class="rect1" width="50px" height="50px"/>
</svg>
</div>
<script type="text/javascript">
document.querySelector("#div1 .rect1").setAttribute("fill","red");
document.querySelector("#div2 .rect1").setAttribute("fill","green");
</script>
</body>
</html>
or .getElementsByClassName() (try on JS Bin):
<html>
<head>
<title></title>
</head>
<body>
<div id="div1">
<svg xmlns="http://www.w3.org/2000/svg" width="50px" height="50px">
<rect class="rect1" width="50px" height="50px"/>
</svg>
</div>
<div id="div2">
<svg xmlns="http://www.w3.org/2000/svg" width="50px" height="50px">
<rect class="rect1" width="50px" height="50px"/>
</svg>
</div>
<script type="text/javascript">
document.getElementById("div1").getElementsByClassName("rect1")[0].setAttribute("fill","red");
document.getElementById("div2").getElementsByClassName("rect1")[0].setAttribute("fill","green");
</script>
</body>
</html>
Probably .querySelector() would also work if you leave the ID attributes as they are, like:
document.querySelector("#div1 [id=rect1]")
but I'd still suggest using data- attributes as this avoids any potential ID pitfalls.
Since you are already using jQuery, you can use jQuery's selectors, which don't care about duplicate ids.
function colorBox(divID, svgElem, colorHex) {
var svgBox = $('#'+divID+' svg').find('#'+svgElem);
svgBox.css("fill", colorHex);
}
Demo here: http://jsfiddle.net/w9KA3/1/

Cannot set opacity to element

I am trying to make and interactive svg which would react to some actions with javascript functions.
My SVG looks like this (this is example of one of many svg I am generating, I deleted some irrelevant elements to make the code more readable):
<svg contentScriptType="text/ecmascript" onmouseover="myOpacity(&apos;msg0&apos;, 0.5)"
onclick="svgClick(&apos;Some example text&apos;)"
width="760" xmlns:xlink="http://www.w3.org/1999/xlink" zoomAndPan="magnify"
onmouseout="myOpacity(&apos;msg0&apos;, 1)"
contentStyleType="text/css" height="30" preserveAspectRatio="xMidYMid meet"
xmlns="http://www.w3.org/2000/svg" version="1.0">
<text fill="black" x="10" id="msg0" font-size="10" y="20">Some text</text>
<script xlink:href="script.js" xlink:actuate="onLoad"
xlink:type="simple" xlink:show="other" type="text/ecmascript"
xmlns:xlink="http://www.w3.org/1999/xlink"/>
</svg>
This is my script.js file with onClick and opacity functions:
function svgClick(text) {
alert(text);
}
function myOpacity(element_id, op_value)
{
element = document.getElementById(element_id);
element.setAttribute('opacity', op_value);
}
The problem is that myOpacity function does not work and nothing happens when I hover over my objects (despite the id should correspond to the argument of the function).
However, the onCLick function works perfectly, so the problem is probably with identifying the element by id.
I am quite stuck here, could you take a look in the code and tell me where did I go wrong?
EDIT: this is a followup from this answer: Interactive SVG - how to choose element to react on mouseover action?
That code works there but it somehow does not do anything in the code I posted here. So my question is why? I know I could do this via attributes, but in that case, I do not know how to handle scenario, when I want to set opacity to one element when mouseover action is triggered on another one...
I pasted your code into a jsFiddle (making the JavaScript inline), and it works without problems in Firefox and Chrome:
http://jsfiddle.net/wpZs6/
However, the hover part could be considerably easier with just a CSS hover selector:
<svg width="760" height="30" xmlns="http://www.w3.org/2000/svg" version="1.0">
<style type="text/css">
svg:hover #msg0 {opacity:.5}
</style>
<text fill="black" x="10" id="msg0" font-size="10" y="20">Some text</text>
</svg>
See here: http://jsfiddle.net/L58z6/
try this :
var divtmp = document.getElementById(element_id);
var newStyle = "filter:alpha(opacity=85);-moz-opacity:0.85; opacity: 0.85;";
divtmp.setAttribute("style", newStyle );

Combining SVG, HTML and Javascript

I have an HTML file that looks somehow like this:
<html>
<div id="test"> ... </div>
<object data="pic.svg" [...]></object>
</html>
Inside pic.svg, I have an element, let's say, a circle, and I want to realize something like that:
<circle onClick="doSomething()" [...]>
Now, in the js function doSomething() (i.e. when someone clicks on the circle) I want to change my "test"-div. How to do this?
You can access the parent document (and consequently the elements there) from inside the svg like this:
var divInParentDocument = window.parent.document.getElementById('test');
Here's a (slightly more complex) example showing how to call a function in the parent html document from inside an svg.
If you want the SVG to live in the same DOM as the HTML, best to use an embedded <svg> element. It's pretty well supported.
Something like
<svg id="svgroot" width="600" height="600"
version="1.1" xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<script type="text/ecmascript">//<![CDATA[
function doSomething() {
document.getElementById('test').appendChild(...);
}
//]]></script>
<circle onClick="doSomething()" />
</svg>

Categories