jquery-svg.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*globals $, jQuery */
  2. /*jslint vars: true */
  3. /**
  4. * jQuery module to work with SVG.
  5. *
  6. * Licensed under the MIT License
  7. *
  8. */
  9. // Dependencies:
  10. // 1) jquery
  11. (function() {'use strict';
  12. // This fixes $(...).attr() to work as expected with SVG elements.
  13. // Does not currently use *AttributeNS() since we rarely need that.
  14. // See http://api.jquery.com/attr/ for basic documentation of .attr()
  15. // Additional functionality:
  16. // - When getting attributes, a string that's a number is return as type number.
  17. // - If an array is supplied as first parameter, multiple values are returned
  18. // as an object with values for each given attributes
  19. var proxied = jQuery.fn.attr,
  20. // TODO use NS.SVG instead
  21. svgns = "http://www.w3.org/2000/svg";
  22. jQuery.fn.attr = function(key, value) {
  23. var i, attr;
  24. var len = this.length;
  25. if (!len) {return proxied.apply(this, arguments);}
  26. for (i = 0; i < len; ++i) {
  27. var elem = this[i];
  28. // set/get SVG attribute
  29. if (elem.namespaceURI === svgns) {
  30. // Setting attribute
  31. if (value !== undefined) {
  32. elem.setAttribute(key, value);
  33. } else if ($.isArray(key)) {
  34. // Getting attributes from array
  35. var j = key.length, obj = {};
  36. while (j--) {
  37. var aname = key[j];
  38. attr = elem.getAttribute(aname);
  39. // This returns a number when appropriate
  40. if (attr || attr === "0") {
  41. attr = isNaN(attr) ? attr : (attr - 0);
  42. }
  43. obj[aname] = attr;
  44. }
  45. return obj;
  46. }
  47. if (typeof key === "object") {
  48. // Setting attributes form object
  49. var v;
  50. for (v in key) {
  51. elem.setAttribute(v, key[v]);
  52. }
  53. // Getting attribute
  54. } else {
  55. attr = elem.getAttribute(key);
  56. if (attr || attr === "0") {
  57. attr = isNaN(attr) ? attr : (attr - 0);
  58. }
  59. return attr;
  60. }
  61. } else {
  62. return proxied.apply(this, arguments);
  63. }
  64. }
  65. return this;
  66. };
  67. }());