0

I have an SVG with a rect child element. The rect child has an onclick event that gets another element by its ID and changes its background color. This works in Chrome on my desktop as well as the iOS emulators in the Chrome inspector. However, it doesn't trigger the event on iOS devices.

What can I change in my code to work on both desktop and iOS devices? Should I be listening for an additional event?

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" style="height: 200px; width: 200px; border: 4px dashed salmon;">
    <rect x="25" y="25" height="50" width="50" style="cursor: pointer; fill: gold;" onclick="getElementById('box').style.backgroundColor = 'gold';"></rect>
</svg>
<div id="box" style="height: 200px; width: 200px; background-color: skyblue;"></div>

Here is a CodePen.

Corey
  • 6,612
  • 4
  • 20
  • 28

3 Answers3

2

Yes, unfortunately there is a bug in iOS - "click" and "tap" events doesn't work within svg tag.

But you can use "touchstart" / "touchend" events - they are work well in iOS with svg.

You can emulate a "tap" event: https://stackoverflow.com/a/32120668/3265404

mike.zimin
  • 39
  • 6
0

You have to call getElementById() as a method of document explicitly:

onclick="document.getElementById('box').style.backgroundColor = 'gold';"
Corey
  • 6,612
  • 4
  • 20
  • 28
  • I would have caught this earlier if it was broken everywhere, but because it only presented itself on the touch devices I was testing, I totally missed the obvious! – Corey Mar 28 '19 at 01:31
0

I was having this issue on Chrome on iOS found that using cursor: pointer; on the svg element made it work.

Source: https://github.com/meteor/meteor/issues/681#issuecomment-351443900

Sam Carlton
  • 1,190
  • 1
  • 17
  • 18