Search code examples
javascriptjqueryhtmlfade

Fade image on scrolling


i'm trying to fade an image on scrolling with the following code:

html:

<img th:src="@{/img/bc.jpg}" class="top" onscroll="myFunction()"/>

css:

.top {
    margin: 0;
    width: 100%;
    height: 100%;
    opacity: 1;
}

js:

<script 
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">

function myFunction() {
var myElement = $('.top');

$(window).on('scroll', function () {
    var st = $(this).scrollTop();
    myElement.css({
        'opacity': 1 - st / 600
    });
});
}

</script>

It wont work, and since its my first time using JQuery, i figured the issue is probably import-wise? I tried to do this without putting the js code in a function aswell, and it didn't work.


Solution

  • First of all you dont need to specify the scroll function in html(inline)

    <img th:src="@{/img/bc.jpg}" class="top"/>
    

    Second your executive code should be in $(document).ready event of jQuery

    <script 
    src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
    
    <script>
        $(document).ready(function() {
           var myElement = $('.top');
           $(window).on('scroll', function () {
             var st = $(this).scrollTop();
             myElement.css({
                'opacity': 1 - st / 600
             });
          });
        });
    </script>
    

    JSFiddle demo link

    That should work