1

How to check if an element it's completely visible in the browser window (viewport) also with ::before ::after pseudo selector creator?

Thanks to this SO answer (How can I tell if a DOM element is visible in the current viewport?) it's simple to evaluate if it's visible by using getBoundingClientRect().

But, if the condition it's this (something like a popup o whatever has a ::before or an ::after declaration in css [open the code snippet in full page to see correctly the example]

function isElementInViewport(el) {
  if (typeof jQuery === "function" && el instanceof jQuery) {
    el = el[0];
  }
  var rect = el.getBoundingClientRect();
  return (
    rect.top >= 0 &&
    rect.left >= 0 &&
    rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /* or $(window).height() */
    rect.right <= (window.innerWidth || document.documentElement.clientWidth) /* or $(window).width() */
  );
}
$(document).ready(function() {
  console.log("Is visible: " + isElementInViewport($(".a")));
})
$(window).on('resize', function() {
  console.log("Is visible: " + isElementInViewport($(".a")));
})
body { background: red; }
.a {
  display: block;
  width: 100px;
  background-color: #555;
  color: #fff;
  text-align: center;
  border-radius: 6px;
  padding: 8px 0;
  position: absolute;
  top: 0px;
  right: 50%;
  margin: 0px;
}

.a::after {
  content: "";
  position: absolute;
  top: 100%;
  left: 50%;
  margin-left: -5px;
  border-width: 105px;
  border-style: solid;
  border-color: #000000 transparent transparent transparent;
}
<script src="https://code.jquery.com/jquery-3.6.1.js"></script>

<div class="a">
  rhfjerjfberhbfj<br> rhfjerjfberhbfj
  <br> rhfjerjfberhbfj
  <br> rhfjerjfberhbfj
  <br> rhfjerjfberhbfj
  <br> rhfjerjfberhbfj
  <br> rhfjerjfberhbfj
  <br> rhfjerjfberhbfj
  <br> rhfjerjfberhbfj
  <br> rhfjerjfberhbfj
  <br> rhfjerjfberhbfj
  <br> rhfjerjfberhbfj
  <br> rhfjerjfberhbfj
  <br> rhfjerjfberhbfj
  <br> rhfjerjfberhbfj
  <br> rhfjerjfberhbfj
  <br> rhfjerjfberhbfj
  <br> rhfjerjfberhbfj
  <br> rhfjerjfberhbfj
  <br> rhfjerjfberhbfj
  <br> rhfjerjfberhbfj
  <br> rhfjerjfberhbfj
  <br> rhfjerjfberhbfj
  <br> rhfjerjfberhbfj
  <br> rhfjerjfberhbfj
  <br> rhfjerjfberhbfj
  <br> rhfjerjfberhbfj
  <br> rhfjerjfberhbfj
  <br> rhfjerjfberhbfj
  <br> rhfjerjfberhbfj
  <br> rhfjerjfberhbfj
  <br> rhfjerjfberhbfj
  <br> rhfjerjfberhbfj
  <br> rhfjerjfberhbfj
  <br> rhfjerjfberhbfj
  <br> rhfjerjfberhbfj
  <br> rhfjerjfberhbfj
  <br> rhfjerjfberhbfj
  <br> rhfjerjfberhbfj
  <br> rhfjerjfberhbfj
  <br>
</div>

it might work better.

So,

How to edit this to get a working function also by considering ::before and ::after size?

user20417316
  • 51
  • 1
  • 4

0 Answers0