znatno
znatno

Reputation: 93

How to find out that the height of the user's device screen is smaller than height of page content?

I'm making a web app in PHP and want to place "Back to top" element in the footer only if user need to scroll the page, in other case it will be not shown. How can I verify that the height of the user's browser screen is too small to display the <body> tag without frameworks?

Right now footer looks like:

    <footer class="container pt-4 my-md-5 pt-md-5 border-top">
    <p class="float-right"><a href="#">Back to top</a></p>
    <p>© 2020 · <a href="#" target="_blank">Telegram</a> · <a href="#" target="_blank">GitHub</a></p>
    </footer>

Upvotes: 1

Views: 158

Answers (2)

znatno
znatno

Reputation: 93

Based on Ahmed's answer. Solution is:

window.addEventListener("DOMContentLoaded", () => {
    let contentHeight = document.getElementsByTagName("body")[0].clientHeight;
    let contentRelativeHeight = contentHeight / window.innerHeight;

    if (contentRelativeHeight <= 1) {
        document.getElementById("to-top-btn").style.display = "none";
    }
});

Upvotes: 1

Ahmed Abdelfattah
Ahmed Abdelfattah

Reputation: 577

You need to calculate content height relative to window height like that

var contentHeight=document.getElementById("content-id").clientHeight

var contentRelativeHeight= contentHieght / window.innerHeight

then check if it lower than or equal 1 (which mean content height less than or equal device screen height) hide back to top button.

<p id="goTopBtn" class="float-right"><a href="#">Back to top</a></p>
if(contentRelativeHeight <= 1){
   document.getElementById("goTopBtn").style.display="none"
}

Upvotes: 1

Related Questions