Neeraj Chimwal
Neeraj Chimwal

Reputation: 57

scrollTop() shows result only after page refresh

Hii I am working on jquery but my code working in a weird manner. Here is my code

$(document).ready(function() {
        if($(window).scrollTop() >= 50) {
            $("h1").fadeIn("slow");
        };
    })

I want my text to fadein when scroll. But my text appear ony after I refresh page after scrolling. I dont know Why what is wrong with my code.

Upvotes: 1

Views: 213

Answers (1)

s.kuznetsov
s.kuznetsov

Reputation: 15223

As I wrote above in the comment, you need to wrap your logic in a window scrolling event. Like this:

$(window).scroll(function() {
    if($(window).scrollTop() >= 50) {
      $("h1").fadeIn("slow");
    }
})

I made an example for you by specifying the position: sticky for the h1 tag so that you can visually understand how the code works.

$(document).ready(function() {
  $(window).scroll(function() {
    if($(window).scrollTop() >= 50) {
      $("h1").fadeIn("slow");
    }
  })
})
body {
  height: 3000px;
}

h1 {
  display: none;
  position: sticky;
  top: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Test_Text</h1>

Upvotes: 1

Related Questions