Jquery Check If Element Is Visible in Viewport

Jquery check if element is visible in viewport

According to the documentation for that plugin, .visible() returns a boolean indicating if the element is visible. So you'd use it like this:

if ($('#element').visible(true)) {
// The element is visible, do something
} else {
// The element is NOT visible, do something else
}

jQuery - Detecting if element is in viewport

Your use of "this" targets window not .blogcard element:

$(window).scroll(function () {
if ($('.blogcard ').isInViewport()) {
// Use .blogcard instead of this
$('.blogcard').addClass('test');
console.log('success.')
} else {
// Remove class
$('.blogcard').removeClass('test');
console.log('No success.')
}
});

Checking if a div is visible within viewport using jquery

Here is the working versions: http://jsfiddle.net/wN7ah/455/

Function that does the magic:

$.fn.isOnScreen = function(){

var win = $(window);

var viewport = {
top : win.scrollTop(),
left : win.scrollLeft()
};
viewport.right = viewport.left + win.width();
viewport.bottom = viewport.top + win.height();

var bounds = this.offset();
bounds.right = bounds.left + this.outerWidth();
bounds.bottom = bounds.top + this.outerHeight();

return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));

};

Usage:

$(window).scroll(function() {
if ($('.orange').isOnScreen() == true) {
//alert("removing orange");
$('.orange').remove();
}
if ($('.red').isOnScreen() == true) {
//alert("removing red");
$('.red').remove();
}

});

If any orange or red is present in onscreen it'll remove them.

If you want to check when it's removed, add alert before removing: http://jsfiddle.net/wN7ah/457/

JavaScript – detect if element stays in viewport for n seconds

I used the jquery-visible plugin to achieve a script that will output the time (in seconds) since a particular element is in view. The output uses an interval of X seconds... out of the scroll handler.

On stop scrolling, we check all the monitored elements to know if they're in the viewport.

If an element is, we check if it already was logged in the visible_begins array on a previous scroll stop. If it isn't, we push an object containing its id and the actual time in milliseconds.

Still on scroll stop, if an element isn't in the viewport, we check if it was logged in the visible_begins and if it's the case, we remove it.

Now on an interval of X seconds (your choice), we check all the monitored elements and each that is still in viewport is outputed with the time differential from now.

console.clear();
var scrolling = false;var scrolling_timeout;var reading_check_interval;var reading_check_delay = 5; // secondsvar completePartial = false; // "true" to include partially in viewportvar monitored_elements = $(".target");var visible_begins = [];

// Scroll handler$(window).on("scroll",function(){ if(!scrolling){ console.log("User started scrolling."); } scrolling = true;
clearTimeout(scrolling_timeout); scrolling_timeout = setTimeout(function(){ scrolling = false; console.log("User stopped scrolling.");
// User stopped scrolling, check all element for visibility monitored_elements.each(function(){ if($(this).visible(completePartial)){ console.log(this.id+" is in view.");
// Check if it's already logged in the visible_begins array var found = false; for(i=0;i<visible_begins.length;i++){ if(visible_begins[i].id == this.id){ found = true; } } if(!found){ // Push an object with the visible element id and the actual time visible_begins.push({id:this.id,time:new Date().getTime()}); } } }); },200); // scrolling delay, 200ms is good.}); // End on scroll handler

// visibility check intervalreading_check_interval = setInterval(function(){ monitored_elements.each(function(){ if($(this).visible(completePartial)){ // The element is visible // Check all object in the array to fing this.id for(i=0;i<visible_begins.length;i++){ if(visible_begins[i].id == this.id){ var now = new Date().getTime(); var readTime = ((now-visible_begins[i].time)/1000).toFixed(1); console.log(visible_begins[i].id+" is in view since "+readTime+" seconds.") }
} }else{ // The element is not visible // Remove it from thevisible_begins array if it's there for(i=0;i<visible_begins.length;i++){ if(visible_begins[i].id == this.id){ visible_begins.splice(i,1); console.log(this.id+" was removed from the array."); } } } });},reading_check_delay*1000); // End interval
.target{  height:400px;  border-bottom:2px solid black;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-visible/1.2.0/jquery.visible.min.js"></script>
<div id="one" class="target">1</div><div id="two" class="target">2</div><div id="three" class="target">3</div><div id="four" class="target">4</div><div id="five" class="target">5</div><div id="six" class="target">6</div><div id="seven" class="target">7</div><div id="eight" class="target">8</div><div id="nine" class="target">9</div><div id="ten" class="target">10</div>

Check if an element is visible on screen

Here is a script returning a promise using the new IntersectionObserver API for checking whether or not an element is actually visible in the viewport:

function isVisible(domElement) {
return new Promise(resolve => {
const o = new IntersectionObserver(([entry]) => {
resolve(entry.intersectionRatio === 1);
o.disconnect();
});
o.observe(domElement);
});
}

Which you can use in your code:

const visible = await isVisible(document.querySelector('#myElement'));
console.log(visible);

Check if element is partially in viewport

Late answer, but about a month ago I wrote a function that does exactly that, it determines how much an element is visible measured in percent in the viewport. Ive tested it in chrome, firefox, ie11, ios on iphone/ipad. The function returns true when X percent (as a number from 0 to 100) of the element is visible. Only determines if the measurements of the element are visible and not if the element is hidden with opacity, visibility etc..

const isElementXPercentInViewport = function(el, percentVisible) {
let
rect = el.getBoundingClientRect(),
windowHeight = (window.innerHeight || document.documentElement.clientHeight);

return !(
Math.floor(100 - (((rect.top >= 0 ? 0 : rect.top) / +-rect.height) * 100)) < percentVisible ||
Math.floor(100 - ((rect.bottom - windowHeight) / rect.height) * 100) < percentVisible
)
};

Check if element with class is visible in viewport

Give the following a try. It loops over the elements to try to find any that match your conditional and if any do, it adds the class. I also added some slight throttling to the solution and also cached the lookups so that the scroll event will be faster.

(function($) {  var scrollingIsThrottled = false;  var $allWhiteSections = $(".white-section");  var $window = $(window);  var $headerContainer = $('.header-container');
$('#content').scroll(function() { if (!scrollingIsThrottled) { scrollingIsThrottled = true;
var $whiteSpaceMatchingExpression = $allWhiteSections.filter(function() { var $this = $(this); var top_of_element = $this.offset().top; var bottom_of_element = $this.offset().top + $this.outerHeight(); var bottom_of_screen = $window.scrollTop() + $window.height(); var top_of_screen = $window.scrollTop();
return ((bottom_of_screen > top_of_element) && (top_of_screen < bottom_of_element)); }); if ($whiteSpaceMatchingExpression.length) { $headerContainer.addClass('alt-menu'); } else { $headerContainer.removeClass('alt-menu'); } scrollingIsThrottled = false; } });}(jQuery));

Check if element is visible in viewport

Here is a small / basic example using Intersection Observer
I hope this will help

// list of elements to be observedconst targets = document.getElementsByClassName('section-page')
const options = { root: null, // null means root is viewport rootMargin: '0px', threshold: 0.5 // trigger callback when 50% of the element is visible}

function callback(entries, observer) { entries.forEach(entry => {
if(entry.isIntersecting){ document.querySelector('.active').classList.remove('active'); const sectionId = entry.target.id; // identify which element is visible in the viewport at 50% document.querySelector(`[href="#${sectionId}"]`).classList.add('active'); } });};
let observer = new IntersectionObserver(callback, options);
[...targets].forEach(target => observer.observe(target));
body {  margin: 0;}
main { margin: 0; display: grid; grid-template-columns: 150px 1fr; font-family: sans-serif; }
#nav { list-style-type: none;}
.navigation-item { color: inherit; text-decoration: none; display: block; margin-bottom: 12px; padding: 5px;}
.navigation-item.active { background-color: grey; color: white; font-weight: bold;}

#sections { height: 100vh; overflow: auto;}
.section-page { margin: 20px; height: 100vh; box-sizing: border-box; padding: 0 20px 20px;}
.section-page:nth-child(1) { background-color: crimson;}
.section-page:nth-child(2) { background-color: darkgreen;}
.section-page:nth-child(3) { background-color: darkorange;}
.section-page:nth-child(4) { background-color: darkblue;}
.content { padding-top: 20px; color: white; position: sticky; top: 0;}
<main>  <nav>    <ul id="nav">      <li>        <a href="#nav-home" class="navigation-item active">HOME</a>      </li>      <li>        <a href="#nav-gallery" class="navigation-item">GALLERY</a>      </li>      <li>        <a href="#nav-info" class="navigation-item">INFO</a>      </li>      <li>        <a href="#nav-contact" class="navigation-item">CONTACT</a>      </li>          </ul>  </nav>  <div id="sections">    <section class="section-page" id="nav-home">      <div class="content">Home section</div>    </section>    <section class="section-page" id="nav-gallery">      <div class="content">Gallery section</div>    </section>    <section class="section-page" id="nav-info">      <div class="content">Info section</div>    </section>    <section class="section-page" id="nav-contact">      <div class="content">Contact section</div>    </section>  </div></main>


Related Topics



Leave a reply



Submit