Jump to content
ben03

Checking If Div Overlaps Browser

Recommended Posts

Hi there,

 I am trying to check whether a div overlaps the browser height using getBoundingClientRect().height and comparing it to window.innerHeight:

css

#container {
min-height: 100vh
}

JS

document.addEventListener("DOMContentLoaded", function() {
    let landingScreen = document.getElementById('container')    
    let getHeight = window.innerHeight
    let landingHeight = landingScreen.getBoundingClientRect().height
    if (landingHeight <= getHeight) {
        do this
    } else {
        do that 
    }
}

However this doesn't seem to always return accurate results. sometimes it considers the div to be the height of the window, even when content is clearly overlapping. Is there a more robust way of achieving this?

Thanks

Share this post


Link to post
Share on other sites

Best to use your developer tools.  That way you can actually see what you're dealing with.

Share this post


Link to post
Share on other sites

Printing to the console shows the div and browser height as the same, despite some of the content of the div spilling out of view. It is almost like it is treating min-height as max-height. Are there possibly some compatibility issues with using 100vh and javascript getBoundingClientRect()?

Share this post


Link to post
Share on other sites

I suspect some margins may be escaping the container. The quick solution to that would be to add overflow: hidden to #container.

Another possibility is that images are changing the height of the container. Since DOMContentLoaded usually fires before images have loaded, the images are not adding to the height of the container at the time that the event fired.

Share this post


Link to post
Share on other sites

Thanks Ingolme, images could well be the problem here. What would be better to use than DOMContentLoaded in this instance?

Share this post


Link to post
Share on other sites

Just the "load" event.

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...