1

So I have an svg#cta-scroll image which is a child of div#main. Whenever I try to get offsetTop (or any other kind of offset) of the svg, it always returns undefined (Chrome, OS X).

(function hideCtaWelcomeOnScroll() {
  var ctaWelcomeElement = document.getElementById('cta-scroll');
  var initialCtaWelcomeOffset = ctaWelcomeElement.offsetTop;
})();

initialCtaWelcomeOffset here always returns undefined.

Does anyone have an idea what might be going on?

EDIT: I don't think it'll help much but here's the CSS for the svg:

#cta-scroll
  width: 2vw
  display: block
  fill: white
  margin-left: -1vw
  position: absolute
  bottom: 7vh
  left: 50%
  z-index: 10
  animation: ctaScroll 10s infinite

In an act of desperation, I tried removing the animation and the positioning but it doesn't change a thing...

8
  • Just a hunch, but it might be that you didn't read How to Ask??
    – Amit
    Commented Jul 8, 2016 at 15:47
  • @Amit What do you mean?
    – Cube.
    Commented Jul 8, 2016 at 15:48
  • Guess it's too much code. I was in a hurry and grabbed the whole function. Sorry for that. I removed the unnecessary listener and indicated the variable that returns undefined.
    – Cube.
    Commented Jul 8, 2016 at 16:06
  • Is the #cta-scroll element on the page at the point this runs?
    – DBS
    Commented Jul 8, 2016 at 16:06
  • 1
    A quick google gives me the impression that offsetTop isn't a valid property of an SVG element. Which is a little weird, but if you have a container element perhaps you could get the offset of that?
    – DBS
    Commented Jul 8, 2016 at 16:12

1 Answer 1

10

Since SVG elements don't support the offsetTop property, you would be best off wrapping the SVG in a div and getting of the offset of that element instead.

e.g.

(function hideCtaWelcomeOnScroll() {
  var ctaWelcomeElement = document.getElementById('svgWrapper');
  var initialCtaWelcomeOffset = ctaWelcomeElement.offsetTop;
})();

HTML:

<div id="svgWrapper">
  <svg></svg>
</div>

Not the answer you're looking for? Browse other questions tagged or ask your own question.