Prakash Thapa
Prakash Thapa

Reputation: 19

why script works from console not in webpage

I tried it from firefox console and works but when putting from webpage don't work why..? Can you please explain about this

if(scrollY > 100){
alert('scrolled over');
}
p{
padding-top:300px;
height:2000px;
}
<body>
<p>Scroll on me</p>
</body>

Upvotes: 0

Views: 54

Answers (2)

Chayemor
Chayemor

Reputation: 3707

The reason why your code works on console is because the moment you press enter it will execute. If you want to have that as a script in your web page, I recommend reading about document loaded and window events, specifically scroll event.

There are various ways you can go about your code, in this case you don't need to wait for the DOM to have loaded, but you do need to bind your function so that it executes every time the user scrolls. I have done a quick snippet that does the following:

  • Binds a function to the scroll event in window

  • Checks if the user has reached scroll position, if so it shows the alert once and waits for the user to scroll up again and will show the message if the user scrolls down. Why? If you just add the if condition you have, it'll show that alert every time the user scrolls past 100, that's terrible (that happens due to binding to the 'scroll' event, since it'll call the function passed every time the user scrolls).

let last_known_scroll_position = 0;
let reached_scroll_pos = false;

window.addEventListener('scroll', function(e) {
  let curr_scroll_pos = window.scrollY;
  
  if(!reached_scroll_pos 
      && curr_scroll_pos > last_known_scroll_position 
      && window.scrollY > 100){ 
        alert("Passed scroll");
        reached_scroll_pos = true;
  } else if (curr_scroll_pos < last_known_scroll_position
          &&   curr_scroll_pos < 100)
          reached_scroll_pos = false;
            
      
  last_known_scroll_position = curr_scroll_pos;    
});
p{
padding-top:300px;
height:2000px;
}
<body>
<p>Scroll on me</p>
</body>

Hope that helps.

Upvotes: 1

pevhv
pevhv

Reputation: 68

I think your problem is that the code runs only once when the page is loaded. You could try different things:

1) use events

2) use the setInterval()

if you want to recieve precise answer provide more code, there is no link between the JS and the HTML in the code you provide.

Upvotes: 1

Related Questions