javascriptscrolltopslideuponscroll

onscroll many times in the same page from different divs


i am trying to create a page where the pictures appear and slightly slide up as you scroll down. I am using this code but i can't make it work for more than one picture and also i can't find a way to specify that the scroll function has to starts from a div and not from the top of the page (i don't know javascript well enough). can anyone help me? thanks

<script>
window.onscroll = function() {myFunction()};

function myFunction() {
    if (document.body.scrollTop > 50 || document.documentElement.scrollTop > 50) {
        document.getElementById("box").className = "slideUp";
    }
}
</script>
<style>
html{width:100%;}

body{height:1500px;}
contenitore{height:890px; width:600px; margin-left:90px; padding:0; float:left; margin-right:90px; margin-top:60px;}

.box{float:left; width:200px; height:200px; margin-top:350px;  }

.box2{float:left; width:200px; height:200px; margin-top:350px; margin-left:100px; visibility:hidden;  }

.box3{float:left; width:200px; height:200px; margin-top:350px; margin:50px;    }


.slideUp {animation-name: slideUp;-webkit-animation-name: slideUp;animation-duration: 1s;-webkit-animation-duration: 1s; visibility: visible;}

@keyframes slideUp {0% {opacity: 0;-webkit-transform: translateY(70%);} 100% {opacity: 1;-webkit-transform: translateY(0%);}}

@-webkit-keyframes slideUp {0% {opacity: 0;-webkit-transform: translateY(70%);} 100% {opacity: 1;-webkit-transform: translateY(0%);}}
</style>
<!DOCTYPE html>
<html>

<body>
<div class="box2">
<div id="box"><img src="img/IMG_2997.jpg" width="100%"></div>
</div>

<div class="box2">
<div id="box"><img src="img/IMG_2983.jpg" width="100%"></div>

</div>


</body>
</html>


Solution

  • You are using getElementById('id') that gets the first element with the specified id, since an id should be unique and only used once in a document.

    To get multiple elements you can use getElementsByClassName('class'), this will return a nodelist you can iterate trough.

    Example:

    var myNodeList = document.getElementsByClassName('class');
    for (var i = 0; i < myNodeList.length; i++) {
      var item = myNodeList[i];
      //do something with item
    }