4

I'm working with jQuery to modify some svg files data on the fly... one of the things I need to do is modify the "viewBox" attribute. When using jQuery as in the snippet below, however, it is doing a toLower() on the attribute so "viewBox" becomes "viewbox". Normally I wouldn't care but this seems to break svg rendering (at least on Mac OS X in the finder and in Safari).

Is there a way to modify this natively in jQuery (via flag or something) or am I going to have to do a string replace afterwards?

var $svg = $('<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1"></svg>');
// do some work here
$svg.attr('viewBox', 0 + ' ' + 0 + ' ' + 288 + ' ' + 288);
1
  • This might not be what you are looking for, but have you considered using XSL for transforming your file? It's a much more common approach... Commented Aug 17, 2010 at 21:36

3 Answers 3

3

You can use the SVG DOM API to set the viewBox:

$svg.each(function(index,node){
    node.viewBox.baseVal.x = 0
    node.viewBox.baseVal.y = 0
    node.viewBox.baseVal.width = 288
    node.viewBox.baseVal.height = 288
})

More info can be found in the SVG specification: http://www.w3.org/TR/SVG/coords.html#ViewBoxAttribute

Sign up to request clarification or add additional context in comments.

1 Comment

I noticed that jquery does not correctly report the updated svg property values when displaying the element from a selector, but the node itself will reflect the changes.
1

Unless you want to modify the library itself, I don't see any way you can avoid doing a string replace.

1 Comment

This was basically what I had to do to get around this issue.
1

What about if you get out of the jQuery object just for setting the attribute. e.g.

var $svg = $('<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1"></svg>');

$svg[0].setAttribute('viewBox', 0 + ' ' + 0 + ' ' + 288 + ' ' + 288);

Note: you may also want to check out this jQuery plugin: http://keith-wood.name/svg.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.