Here is my codes:
Javascript:
document.body.onload = function() {
function UP() {//Ẩn hiện nút UP
if(window.pageYOffset > window.innerHeight)
document.getElementById('UP').style.display = "block";
}
}
HTML tag:
<button id="UP" onclick="toTop(350);"></button>
CSS style:
#UP {display: none;}
My idea is when I scroll down, then UP button will appear. But don't know why, it won't, it even return the error: "Uncaught TypeError: Cannot set property 'document.body' of null". Of couse, I did change other script like this:
function getReady() {
UP();
}
function UP() {//Ẩn hiện nút UP
if(window.pageYOffset > window.innerHeight)
document.getElementById('UP').style.display = "block";
}
HTML tag:
<body onload="getReady();">
<button id="UP" onclick="toTop(350);"></button>
</body>
It is even more terrible. When I load site, I didn't see onload attr of body tag and the browser didn't return any error for me.
Some other infomation: I develop on both side, Cr & FF, it all says a same problem. And I'm working on Wordpress source.
Just to clarify @laruiss and explain what is going on, lets start with your code:
When using the onload event, you are actually doing the right thing. True, it's not recommended to actually do that in your DOM, but it should work. The biggest issue that DOM load is subjective. Some browsers will consider the body loaded as soon as the content is in, others will wait for images, and older IE versions won't fire it all! So if you use the recommended
window.onload
, you should be fine, as it will fire as soon as the DOM is ready. There is another great event for this you might want to consider, which isDOMContentLoaded
, but its not as widely supported. Theres a bit more (by clicking through as well) here: https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers.onloadI would also like to add that even though you put your button to display, its has no content so it could appear either empty or if you are resetting your button styles, not at all. Something to keep in mind.