I want to create a script in which i want to increase the margin-top of the image on scrolling down the page and vice-versa, but i cant understand where to put the event listener.
So,That when scrolling down the page, the image moves with the scroll and stops before the green div.
document.getElementById("body").addEventListener("scroll", myFunction); function myFunction() { console.log('scrolled'); }
#body{ width:100%; height:3000px; } #yellowdiv { width:100%; height:1000px; background-color: yellow; } #image { width:50%; height:500px; border: 10px solid black; } #bluediv { width:100%; height:1000px; background-color: blue; } #pinkdiv { width:100%; height:1000px; background-color: pink; } #greendiv { width:100%; height:1000px; background-color: green; }
<div id="body"> <div id="yellowdiv"> <img id="image"src="#"> </div> <div id="bluediv"> </div> <div id="pinkdiv"> </div> <div id="greendiv"> </div> </div>
P.S – new to JS
Thanks in Advance.
Answer
You are trying to attach the event handler to the #body
div but you are not scrolling the div, you are scrolling the window
.
If you want to attach a scroll-event handler to the div, it must be scrollable. Below you can find an example with a wrapper div #scrollable
and the event handler is attached to it.
document.getElementById("scrollable").addEventListener("scroll", myFunction); function myFunction() { console.log('scrolled'); }
#scrollable { height: 100px; overflow-y: auto; } #body { width: 100%; height: 3000px; } #yellowdiv { width: 100%; height: 1000px; background-color: yellow; } #image { width: 50%; height: 500px; border: 10px solid black; } #bluediv { width: 100%; height: 1000px; background-color: blue; } #pinkdiv { width: 100%; height: 1000px; background-color: pink; } #greendiv { width: 100%; height: 1000px; background-color: green; }
<div id="scrollable"> <div id="body"> <div id="yellowdiv"> <img id="image" src="#"> </div> <div id="bluediv"> </div> <div id="pinkdiv"> </div> <div id="greendiv"> </div> </div> </div>