0

var parent = document.getElementById("parent").children;
for (var i = 0; i < parent.length; i++) {
  var m = Math.floor((Math.random() * 300) + 100);
  console.log(m);
  parent[i].style.margin = m+'px 0 0 0';
}
#parent div {
    display: block;
    height: 200px;
    width: 200px;
    text-align: center;
    vertical-align: middle;
    font-size: 100px;
    background-color: black;
    color: white;
}
<div id="parent">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
</div>

how can i tell if i scrolled on top of one of the child divs?

i tried using

parent.onscroll = function(){
  ... ... ...
}

but it does not work at all because it does not tell if scrolled on the children or not

Joe Doe
  • 513
  • 2
  • 8
  • 1
    Are you asking how to tell if a child div is in your viewport? – Nick Parsons Nov 02 '19 at 07:32
  • @NickParsons if scrolled on top of **div 1** to `consol.log` is in view but once and to `consol.log` again only if **other div** was in view of the divs – Joe Doe Nov 02 '19 at 07:33
  • @NickParsons i tried `function isScrolledIntoView(el)` and it worked like i want but i do not know how to apply it forever while scrolling to `consol.log('now you are scrolling div'+i)` dynamically – Joe Doe Nov 02 '19 at 07:54
  • 1
    Feel free to check my answer here: [How detect which child element is visible after scrolling the parent div?](https://stackoverflow.com/questions/56999795/how-detect-which-child-element-is-visible-after-scrolling-the-parent-div) – icecub Nov 02 '19 at 07:59
  • 1
    @JoeDoe maybe something like this is what you're after: https://jsfiddle.net/n1m86u0a/ This does loop through all child div each time we scroll, so it's not the very efficient – Nick Parsons Nov 02 '19 at 08:06
  • @NickParsons yes worked all - is tracking scroll really inefficient and i should not use it? it eats cpu a lot – Joe Doe Nov 02 '19 at 08:08
  • 1
    @JoeDoe The answer to the question I've linked pretty much simulates Word / Adobe PDF Reader behaviour. Based on the amount of pixels visible, it tells you which child div is currently being scrolled. It's called "pages" in that answer, but you can change it to anything you want and / or use that number any way you see fit. It (should) work perfectly fine with different div sizes just as well. It's still a bit CPU intensive though because it has to calculate on every scroll event. – icecub Nov 02 '19 at 08:13

0 Answers0