Jquery check if element is visible in viewport [duplicate] - javascript

This question already has answers here:
How to check if element is visible after scrolling?
(46 answers)
Closed 5 years ago.
Function to check if the div class "media" is within the browsers visual viewport regardless of the window scroll position.
<HTML>
<HEAD>
<TITLE>My first HTML document</TITLE>
</HEAD>
<BODY>
<div class="main">
<div class="media"></div>
</div>
</BODY>
</HTML>
Trying to use this plugin https://github.com/customd/jquery-visible with this function but
I don't know how to make it work.
$('#element').visible( true );

You can write a jQuery function like this to determine if an element is in the viewport.
Include this somewhere after jQuery is included:
$.fn.isInViewport = function() {
var elementTop = $(this).offset().top;
var elementBottom = elementTop + $(this).outerHeight();
var viewportTop = $(window).scrollTop();
var viewportBottom = viewportTop + $(window).height();
return elementBottom > viewportTop && elementTop < viewportBottom;
};
Sample usage:
$(window).on('resize scroll', function() {
if ($('#Something').isInViewport()) {
// do something
} else {
// do something else
}
});
Note that this only checks the top and bottom positions of elements, it doesn't check if an element is outside of the viewport horizontally.

Check if element is visible in viewport using jquery:
First determine the top and bottom positions of the element. Then determine the position of the viewport's bottom (relative to the top of your page) by adding the scroll position to the viewport height.
If the bottom position of the viewport is greater than the element's top position AND the top position of the viewport is less than the element's bottom position, the element is in the viewport (at least partially). In simpler terms, when any part of the element is between the top and bottom bounds of your viewport, the element is visible on your screen.
Now you can write an if/else statement, where the if statement only runs when the above condition is met.
The code below executes what was explained above:
// this function runs every time you are scrolling
$(window).scroll(function() {
var top_of_element = $("#element").offset().top;
var bottom_of_element = $("#element").offset().top + $("#element").outerHeight();
var bottom_of_screen = $(window).scrollTop() + $(window).innerHeight();
var top_of_screen = $(window).scrollTop();
if ((bottom_of_screen > top_of_element) && (top_of_screen < bottom_of_element)){
// the element is visible, do something
} else {
// the element is not visible, do something else
}
});
This answer is a summary of what Chris Bier and Andy were discussing below. I also used an answer to the following question to formulate my answer: Show Div when scroll position.

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
}

You can see this example.
// Is this element visible onscreen?
var visible = $(#element).visible( detectPartial );
detectPartial :
True : the entire element is visible
false : part of the element is visible
visible is boolean variable which indicates if the element is visible or not.

var visible = $(".media").visible();

Related

Start counter with a little delay [duplicate]

This question already has answers here:
How to check if element is visible after scrolling?
(46 answers)
Closed 5 years ago.
Function to check if the div class "media" is within the browsers visual viewport regardless of the window scroll position.
<HTML>
<HEAD>
<TITLE>My first HTML document</TITLE>
</HEAD>
<BODY>
<div class="main">
<div class="media"></div>
</div>
</BODY>
</HTML>
Trying to use this plugin https://github.com/customd/jquery-visible with this function but
I don't know how to make it work.
$('#element').visible( true );
You can write a jQuery function like this to determine if an element is in the viewport.
Include this somewhere after jQuery is included:
$.fn.isInViewport = function() {
var elementTop = $(this).offset().top;
var elementBottom = elementTop + $(this).outerHeight();
var viewportTop = $(window).scrollTop();
var viewportBottom = viewportTop + $(window).height();
return elementBottom > viewportTop && elementTop < viewportBottom;
};
Sample usage:
$(window).on('resize scroll', function() {
if ($('#Something').isInViewport()) {
// do something
} else {
// do something else
}
});
Note that this only checks the top and bottom positions of elements, it doesn't check if an element is outside of the viewport horizontally.
Check if element is visible in viewport using jquery:
First determine the top and bottom positions of the element. Then determine the position of the viewport's bottom (relative to the top of your page) by adding the scroll position to the viewport height.
If the bottom position of the viewport is greater than the element's top position AND the top position of the viewport is less than the element's bottom position, the element is in the viewport (at least partially). In simpler terms, when any part of the element is between the top and bottom bounds of your viewport, the element is visible on your screen.
Now you can write an if/else statement, where the if statement only runs when the above condition is met.
The code below executes what was explained above:
// this function runs every time you are scrolling
$(window).scroll(function() {
var top_of_element = $("#element").offset().top;
var bottom_of_element = $("#element").offset().top + $("#element").outerHeight();
var bottom_of_screen = $(window).scrollTop() + $(window).innerHeight();
var top_of_screen = $(window).scrollTop();
if ((bottom_of_screen > top_of_element) && (top_of_screen < bottom_of_element)){
// the element is visible, do something
} else {
// the element is not visible, do something else
}
});
This answer is a summary of what Chris Bier and Andy were discussing below. I also used an answer to the following question to formulate my answer: Show Div when scroll position.
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
}
You can see this example.
// Is this element visible onscreen?
var visible = $(#element).visible( detectPartial );
detectPartial :
True : the entire element is visible
false : part of the element is visible
visible is boolean variable which indicates if the element is visible or not.
var visible = $(".media").visible();

how to determine whether a particular row is present in the viewport of table body or not [duplicate]

This question already has answers here:
How to check if element is visible after scrolling?
(46 answers)
Closed 5 years ago.
Function to check if the div class "media" is within the browsers visual viewport regardless of the window scroll position.
<HTML>
<HEAD>
<TITLE>My first HTML document</TITLE>
</HEAD>
<BODY>
<div class="main">
<div class="media"></div>
</div>
</BODY>
</HTML>
Trying to use this plugin https://github.com/customd/jquery-visible with this function but
I don't know how to make it work.
$('#element').visible( true );
You can write a jQuery function like this to determine if an element is in the viewport.
Include this somewhere after jQuery is included:
$.fn.isInViewport = function() {
var elementTop = $(this).offset().top;
var elementBottom = elementTop + $(this).outerHeight();
var viewportTop = $(window).scrollTop();
var viewportBottom = viewportTop + $(window).height();
return elementBottom > viewportTop && elementTop < viewportBottom;
};
Sample usage:
$(window).on('resize scroll', function() {
if ($('#Something').isInViewport()) {
// do something
} else {
// do something else
}
});
Note that this only checks the top and bottom positions of elements, it doesn't check if an element is outside of the viewport horizontally.
Check if element is visible in viewport using jquery:
First determine the top and bottom positions of the element. Then determine the position of the viewport's bottom (relative to the top of your page) by adding the scroll position to the viewport height.
If the bottom position of the viewport is greater than the element's top position AND the top position of the viewport is less than the element's bottom position, the element is in the viewport (at least partially). In simpler terms, when any part of the element is between the top and bottom bounds of your viewport, the element is visible on your screen.
Now you can write an if/else statement, where the if statement only runs when the above condition is met.
The code below executes what was explained above:
// this function runs every time you are scrolling
$(window).scroll(function() {
var top_of_element = $("#element").offset().top;
var bottom_of_element = $("#element").offset().top + $("#element").outerHeight();
var bottom_of_screen = $(window).scrollTop() + $(window).innerHeight();
var top_of_screen = $(window).scrollTop();
if ((bottom_of_screen > top_of_element) && (top_of_screen < bottom_of_element)){
// the element is visible, do something
} else {
// the element is not visible, do something else
}
});
This answer is a summary of what Chris Bier and Andy were discussing below. I also used an answer to the following question to formulate my answer: Show Div when scroll position.
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
}
You can see this example.
// Is this element visible onscreen?
var visible = $(#element).visible( detectPartial );
detectPartial :
True : the entire element is visible
false : part of the element is visible
visible is boolean variable which indicates if the element is visible or not.
var visible = $(".media").visible();

How to scroll a table inside a div on load without scrolling the page

I have a page that had dropdown and images at the top, then a price grid at the bottom (bellow the fold). The price grid is scroll-able inside a div element. On load there is a price on the grid selected, but it is hidden, so you have to scroll the table down to see it.
My problem is, I want to scroll the table within the div element to show the active - but I do not want to scroll the page as well. On load the user should not see anything moving, the table should scroll to show the without them aware (below the fold). When they scroll down the page they should then see the table is displaying the active (selected price) and the table will be scrolled.
const activeRow = $('#prices_table').find('tr td.active');
activeRow[0].scrollIntoView({block: 'center', behavior: 'smooth' });
The problem with my code is it scrolls the user down to the price grid and then scrolls the price grid. I want the user to be left to scroll down to the price grid themselves.
I have found many similar questions, all of these result in the whole page scrolling to the div, and then the div scrolling to show the active class. I need a solution where the page does not scroll.
I have no come up with a solution in JQuery.
var hasScrolled = false;
function isInViewport() {
if (!hasScrolled) {
var elem = $('#prices_table');
if (elem !== undefined) {
var elementTop = elem.offset().top;
var elemBottom = elementTop + elem.outerHeight();
var viewportTop = $(window).scrollTop();
var viewportBottom = viewportTop + $(window).height();
// return elemBottom > viewportTop && elemTop < viewportBottom;
if (elemBottom > viewportTop && elementTop < viewportBottom) {
var activeRow = $('#prices_table').find('tr td.active');
var containerToScroll = $('#prices_table').find('tbody');
var tdHeight = activeRow.outerHeight();
if (activeRow) {
if (activeRow[0] !== undefined{
$(containerToScroll).scrollTop(($('#prices_table').find('tr td.active').offset().top - $('#prices_table').find('tbody').offset().top) - (tdHeight * 2));
hasScrolled = true;
}
}
}
}
}
}
$(window).scroll(function() {
isInViewport('#prices_table');
});
I have a few variables to check before actually scrolling, as sometimes the element is in the correct place on load, and once it has scrolled once I don't want it to move.
On Scroll I now check if element is in view.
I then check if element has previously scrolled, if it hasn't then I will continue.
I set element, if it doesn't exist then I don't continue.
I do some calculations to check the difference the scroll needs to move, if there is no difference I don't continue.
I then do my calculation and update variable hasScrolled to true so this never fires again.
Bit of a longer approach than I was looking for but it works a treat.

How do I code JQuery so that when I scroll to a certain element, Nav bar appears at top, when I scroll back up past that element, nav bar disappears

I have a div called #menu which I want to display when I scroll past the element #section3, if I scroll up past that element again, I want #menu to disappear
How would I code this?
Maybe something like this?
scrolled = "no"
$(window).scroll(function(){
scr = $("body").scrollTop();
if (scr > 100 && scrolled == "no"){
$("#menu").css({"display:block"})
displayed = "yes"
}
if (displayed == "yes" && scrolled = "yes"){
$("#menu").css({"display:none"})
}
});
The above assumes that #section3 is 100 pixels down the page. If you do not know where its going to be on the page then you could use the method outlined here:
Trigger event when user scroll to specific element - with jQuery
With jQuery you can get the scroll position with $("body").scrollTop();.
Expanding on what #Ned Hulton said, I recommend comparing the scroll position to the top of a "container element" (or 'row') in your page like this:
if ($('body').scrollTop() > $('#someRow').offset().top){
//do something
}
That way you can account for your container appearing at a variable distance down the page (which will come in handy for mobile browsing or cases where your text wraps to additional lines)
I just whipped this up in jsfiddle
https://jsfiddle.net/rb56j0yu/
it uses jQuery, and checks the scroll position against the target div. Css sets the menu as position: fixed, and defaults to hidden.
$(window).scroll(function(){
var yPos = $("body").scrollTop();
var yCheck = $("#c3").position().top;
if (yPos > yCheck && !$("#menu").is(":visible"))
{
$("#menu").show();
}
if (yPos <= yCheck && $("#menu").is(":visible"))
{
$("#menu").hide();
}
});
First, get your #section3 top offset and height. Which will be used as the threshold whether #section3 is actually on the window screen.
var top = $('#section3').offset().top;
var bot = topOffset + $('#section3').height();
Then, detect it on your scroll event.
$(window).on('scroll', function () {
var scrollTop = $(window).scrollTop();
if (scrollTop >= top && scrollTop <= bot) {
// #section3 is within the screen.
$('#menu').show();
}
else {
// #section3 is out of screen.
$('#menu').hide();
}
});
This is a common use case, I wrote following code:
// what does "Auto Header" mean, goto https://www.yahoo.com/
// scroll down and you will see the purple part auto fixed to top,
// while when scroll up, it restores and does not be fixed.
// 1. multiple auto header elements handled
// 2. dynamically create/remove elements issue handled
// 3. no unnecessary dom operation, high performance
// usage: just add 'class="auto-header"' to any element you want to auto header
// suggest set each auto-header element specific width and height
// do not guarantee it works when resize or scroll left/right
$(document).ready(function() {
var rawTops = [],
rawLefts = [],
rawStyles = [],
$locations = [], // record next sibling so that element easily find where to restore
fixed = []; // mark whether this element is fixed
$(".auto-header").each(function() {
var $this = $(this),
offset = $this.offset();
rawTops.push(offset.top);
rawLefts.push(offset.left);
rawStyles.push($this.attr("style"));
$locations.push($this.siblings().eq($this.index()));
fixed.push(false);
});
$(window).on("scroll", function() {
$(".auto-header").each(function(i, e) {
if(!fixed[i] && $(window).scrollTop() > rawTops[i]) {
var $te = $(this).clone(true);
$(this).remove();
$locations[i].before($te);
$te.css({
"position": "fixed",
"top": 0,
"left": rawLefts[i],
"z-index": 100
});
fixed[i] = true;
} else if(fixed[i] && $(window).scrollTop() < rawTops[i]) {
$(this).removeAttr("style").attr("style", rawStyles[i]);
fixed[i] = false;
}
});
});
});

JQuery Add Class when bottom of div reaches top

I am trying to add a class when the bottom of a div reaches the top of the window, but am not sure of how to do it.
I have managed to add the class when the top of the div gets to the top of the window, but am not having much luck with the bottom of the div.
Code I am using:
$(document).ready(function() {
var menuLinksTop = $('.container').offset().top;
var menuLinks = function(){
var scrollTop = $(window).scrollTop();
if (scrollTop > menuLinksTop) {
$('header').addClass('black-links');
} else {
$('header').removeClass('black-links');
}
};
menuLinks();
$(window).scroll(function() {
menuLinks();
});
Any help is appreciated.
You should use javascript's getBoundingClientRect() method, watch $(window).scroll event, and look at element's rectangle, its bottom value will give you what you need (if it's negative, your element is all the way up)
$(window).scroll(function() {
console.log($("div.watch")[0].getBoundingClientRect());
if ($("div.watch")[0].getBoundingClientRect().bottom < 0)
alert ("i'm out :3");
});
see jsFiddle http://jsfiddle.net/ja5nnbwr/2/
Add the height of the div. Assuming it is the .container :
var menuLinksTop = $('.container').offset().top + $('.container').height();

Categories