SemicolonExpected
SemicolonExpected

Reputation: 614

JQuery .scroll() event to show hidden object does not work

I'm using .scroll() in order to make the image #mag visible once I scroll past a certain point.

            $(window).scroll(function() {
                var y_scroll_pos = window.pageYOffset;
                var scroll_pos_test = 1000;             

                if(y_scroll_pos > scroll_pos_test) {
                    $("#mag").css("visibility","visible");
                }
            });

        <img id= "mag" src="assets/maginatransparent.png" style = "visibility: hidden; position: fixed; height: 40vh; bottom: 30vh; right: 0">

When I run this, I get no errors, but the event doesn't seem to have been triggered even when I scroll past 1000px.

JSFiddle Link: https://jsfiddle.net/k04qck9h/ Note this uses a span instead of an img.

Upvotes: 0

Views: 217

Answers (1)

Mohamed-Yousef
Mohamed-Yousef

Reputation: 24001

You need to use $(window).scrollTop();

   $(window).scroll(function() {
        var y_scroll_pos = $(window).scrollTop();
        var scroll_pos_test = 1000;             

        if(y_scroll_pos > scroll_pos_test) {
            $("#mag").css("visibility","visible");
        }else{
            $("#mag").css("visibility","hidden");
        }
    });

DEMO

Upvotes: 2

Related Questions