Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
122
rated 0 times [  129] [ 7]  / answers: 1 / hits: 63215  / 9 Years ago, sat, april 18, 2015, 12:00:00

I want to execute the window onscroll event, but I don't know why it doesn't work on all browsers(firefox, chrome, etc), and there is no errors occurred.



Full code:



var elem = document.getElementById('repeat');
var show = document.getElementById('show');

for (i = 1; i <= 300; i++) {
elem.innerHTML += i + <br/>;
}


window.onscroll = function () {
show.innerHTML = document.body.scrollTop;
};

#show {
display:block;
position:fixed;
top:0px;
left:300px;
}

<pre id=repeat></pre>

<div style=position:relative;>
<div id=show>x</div>
</div>





Also jsfiddle:
http://jsfiddle.net/sqo0140j



What is the problem ?


More From » events

 Answers
12

You said something interesting:




x changed to 0 and remains as is.




The only way in your code that can happen is if the onscroll function block makes a change because your HTML sets x.



If your window.onscroll = function() is indeed firing, but you are not getting the right scroll position (i.e. 0), try changing the way the scroll position is returned:



window.onscroll = function () {
show.innerHTML = document.documentElement.scrollTop || document.body.scrollTop;
};


I found out that document.documentElement.scrollTop always returns 0 on Chrome. This is because WebKit uses body for keeping track of scrolling, but Firefox and IE use html.



Please try your updated snippet:





var elem = document.getElementById('repeat');
var show = document.getElementById('show');

for (i = 1; i <= 300; i++) {
elem.innerHTML += i + <br/>;
}


window.onscroll = function () {
show.innerHTML = document.documentElement.scrollTop || document.body.scrollTop;
};

#show {
display:block;
position:fixed;
top:0px;
left:300px;
}

<pre id=repeat></pre>

<div style=position:relative;>
<div id=show>x</div>
</div>




[#67019] Thursday, April 16, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
chyanne

Total Points: 208
Total Questions: 120
Total Answers: 110

Location: Colombia
Member since Mon, May 2, 2022
2 Years ago
;