4

I'm using beginElement() to start an SVG animation in my web app:

document.getElementById("item").beginElement();

But this causes the following error in IE9 and up (which doesn't support it):

Object doesn't support property or method 'beginElement'

I don't mind the animation not working in IE9, but I need to prevent the error from occurring. How do I set up a check so that beginElement() only gets called if the browser supports it? E.g.:

if (hasSupport) {
    document.getElementById("item").beginElement();
}

I tried a detection technique like this:

return !!document.getElementById("item").beginElement();

But that always returns false, even in browsers that I know support it (like Firefox).

I also looked at using Modernizr, but it doesn't have a test for beginElement().

daGUY
  • 27,055
  • 29
  • 75
  • 119
  • Modernizr has a test for [SMIL](http://modernizr.com/docs/#features-misc), that you could use, though it's a little more general. But there's no real point in checking for `beginElement` if SMIL isn't supported as well. – Erik Dahlström Oct 15 '14 at 12:39

1 Answers1

4

You can sniff the method to see if it exists before executing it.

var item = document.getElementById("item");

if ('beginElement' in item) {
    item.beginElement();
}

Modernizr uses in form, however if (item.beginElement) would work just the same.

Patrick
  • 13,872
  • 5
  • 35
  • 53