Skip to content

Commit

Permalink
Update svg.md
Browse files Browse the repository at this point in the history
  • Loading branch information
MichaelCurrin authored Aug 28, 2024
1 parent c5cf78d commit f94f6e7
Showing 1 changed file with 45 additions and 7 deletions.
52 changes: 45 additions & 7 deletions cheatsheets/javascript/browser/svg.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

### Inline SVG

Change using `onclick` to set an attribute or class.

[source](https://stackoverflow.com/questions/9872947/changing-svg-image-color-with-javascript)

```xml
Expand All @@ -12,21 +14,57 @@
<circle id="circle1" r="30" cx="34" cy="34"
style="fill: red; stroke: blue; stroke-width: 2"/>
</svg>
```

```xml
<button onclick="circle1.style.fill='yellow';">
Click to change to yellow
</button>
```

Or better, using a CSS class:

<!-- CSS should be used here instead of editing style. -->
<button onclick="circle1.style.fill='yellow';">Click to change to yellow</button>
```xml
<button onclick="circle1.classList.toggle('yellow-fill');">
Click to change to yellow
</button>
```

```css
circle {
fill: blue;
}

.yellow-fill {
fill: yellow;
}
```


### Linked SVG

Note: styling on the object element does not affect the value inside. An iframe can be used too.
When you embed an SVG using `<object>`, the SVG is treated as a separate document. The `contentDocument` property allows you to access and manipulate this embedded document's DOM (and is safer and more widely used than `getSVGDocument()`).

Set this using JS.

```html
<object id="my-svg" data="image.svg" type="image/svg+xml"></object>
<object id="my-svg" data="image.svg" type="image/svg+xml" onclick="changeFillColor"></object>
```

```javascript
let object = document.getElementById('my-svg');
svg = object.getSVGDocument();
svg.getElementsByTagName('g')[0].setAttribute('fill', '#fff');
function changeFillColor() {
const object = document.getElementById('my-svg');
const svg = object.contentDocument;
const group = svg.getElementsByTagName('g')[0];

group.classList.toggle('white-fill');
}
```

```css
.white-fill {
fill: #fff;
}
```

Note: changing `styling` on the `object` element does not affect the value inside it.

0 comments on commit f94f6e7

Please sign in to comment.