JavaScript: Trying to get clicked element's distance to top of its parent container. Not doing something right.
Hey folks, I've searched around and have found a handful of resources attempting to explain how to solve my problem, but I can't seem to do something right, so I've come to you all for some help.
**Problem**: When a child element inside of a container is clicked, get the distance that element is from the top of the container.
So, for instance, if the first row is clicked upon, and that row has not been scrolled away from the top, it would return 0, whereas each subsequent row `n` would return `indexOf(n) * height(n)` *(pseudo)*
The container has a fixed `height` with `overflow` set to `auto` to enable scrolling when necessary.
**Here's a [CodePen](http://codepen.io/anon/pen/rrodkv)**
**Issue**: I can't seem to get anything other than a zero-value returned.
Any insight is absolutely appreciated.
Also, here's some code if you prefer not to navigate to the CodePen thing:
**HTML**
<div id="container"> <div class="content-row">One</div> <div class="content-row">Two</div> <div class="content-row">Three</div> <div class="content-row">Four</div> <div class="content-row">Five</div> <div class="content-row"></div> <div class="content-row"></div> <div class="content-row"></div> <div class="content-row"></div> <div class="content-row"></div> <div class="content-row"></div> <div class="content-row"></div> <div class="content-row"></div> <div class="content-row"></div> <div class="content-row"></div> </div>
**CSS**
#container { height: 300px; width: 500px; overflow: auto; margin-top: 30px; margin-left: 20px; }
.content-row { height: 50px; width: 100%; background-color: blue; }
.content-row + .content-row { border-top: 1px solid white; }
**JavaScript**
var container = document.getElementById('container');
container.addEventListener("click", function(event) { // Just checking if target is indeed row I clicked console.debug(event.target.innerHTML);
// Get row's distance to top of its parent container console.debug(event.target.scrollTop); });