Get position relative to browser window - javascript

I have 2 divs and one is nested in the other. I want to get the child div position relative to browser window. The use case is this: when user scroll down browser, I want to detect the position of the child div and if it is 100px above the bottom of the browser window, I want to fade it out slowly.
How do I do that with jQuery? The 2 divs have relative position or absolution position but not fixed position.

Try this:
$(window).scroll(function () {
var distanceFromBottom = 100;
if ( ( $("#outerdiv").offset().top + $("#innerdiv").height() - $(window).scrollTop() ) > $(window).height() - distanceFromBottom ) {
$("#innerdiv").fadeOut("slow");
} else {
$("#innerdiv").fadeIn("slow");
}
})
You didn't state if you wanted the #innerdiv to fade back in if greater than 100 pixels from the bottom, but I wrote this assuming that you did... In this case, you would need to detect the offset of the #outerdiv if you want the #innerdiv to fade back in as an invisible element has no position.
If you don't want the #innerdiv to fade back in then change the if statement to look at the #innerdiv element and remove the else portion of the function.
Edit: Looking at your example page, I'm guessing you wanted this effect to work on the music player. Since, it's probably not the best idea to fade or slowly hide an embedded object using jQuery - it just doesn't animate well - so, I just did it abruptly. The above script will still work, but as you can see in the revision below, you don't have to use 2 Divs, I used the div and the embedded object within it. The outer div should closely wrap the inner div for this script to work, so you can't use the div with id "container-msg" in this case.
$(window).scroll(function () {
var distanceFromBottom = 100;
if ( ( $(".windowMediaPlayer").offset().top + $(".windowMediaPlayer object").height() - $(window).scrollTop() ) > $(window).height() - distanceFromBottom ) {
$(".windowMediaPlayer object").hide();
} else {
$(".windowMediaPlayer object").show();
}
})
I modified your example and saved it to this pastebin so you can see it working.
Edit: Oops, you said you wanted it to disappear when it got closer to the bottom... I just changed the "<" to ">" and now it should do what you want. I updated the pastebin code too.

var inner_offset = $("#innerdiv").offset();
var window_size = $(window).height();
if( ( inner_offset.top + $("#innerdiv").height() ) > window_size - 100 )
$("#innerdiv").fadeOut("slow");
Not vetted, but should give you the general idea.

offset at the
jQuery documentation

Related

Detect when the end of a div is visible

I need to know if the end of a div element is currently visible in the users' browser.
I tried something I saw on the web, but scrollTop() always gave me zero in my Browser. I read something about an issue in Chrome, but I didn't understand quite well.
jQuery(
function($) {
$('#flux').bind('scroll', function() {
if ($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) {
alert('end reached');
}
})
}
);
My idea is the following:
1- User loads page and sees a Bar (sticky div at bottom visible page) with some information.
2- After scrolling a bit, and reaching the end of a div element, this bar will position there, after the div. This is the bar's original position
I wasn't really able to know when I was at the end of the div element. Eventually I found this code:
if ($(window).scrollTop() >= $('#block-homepagegrid').offset().top + $('#block-homepagegrid').outerHeight() - window.innerHeight) {
$('.hero-special-message').removeClass('hero-special-messege-scrolling');
} else {
$('.hero-special-message').addClass('hero-special-messege-scrolling');
}
});
I see that it's working, but I'm having a bit of trouble understanding what it does.
I know the following:
1. $(window).scrollTop();
this gives me the amount of pixels the user has scrolled, pretty self explanatory.
2. $('#block-homepagegrid').offset().top;
I THINK this is the distance between the start of the page and the start of the div. I know it's the current coordinates, but what is top exactly here?
3. $('#block-homepagegrid').outerHeight();
this gives the height of the element, I know there are 3, like
height(), innerHeight() and outerHeight(), if you want to take into
account border, margin, padding, which is the better to use?
4. window.innerHeight;
I understand this is what the user sees, but I'm having troubles understanding why does it matter for my situation.
Thanks!
You may be interested in the native JavaScript IntersectionObserver API. It automatically figures out what percentage of a given element is visible in the window and triggers callbacks based on that. So then you can do this:
function visibleHandler(entries) {
if (entries[0].intersectionRatio >= 1.0) {
// The whole element is visible!
} else {
// Part of it is scrolled offscreen!
}
}
const observer = new IntersectionObserver(visibleHandler, {threshold: 1.0});
observer.observe(document.getElementById('flux'));
Now, whenever the element with ID flux is 100% in view, it will trigger the visibleHandler. It will also trigger again if it's scrolled back out of view; that's why the function checks the ratio of visibility to see if it just hit 100% or just got reduced from 100%. You could be more fancy and use the observer entry's insersectionRect, which gives you the rectangle containing the visible portion of the element, and use that to determine top/bottom visibility.

Hide a div until scrolled to the bottom of the page

I am making a web page (kind of like those music release pages, here is an example), and I would like certain div's at the bottom not to be shown until the user has scrolled to the bottom of the page, delay a second or two, then pop up. Kind of like a hidden feature thing.
You can also think of it like an infinite scroll, like when you drag down your Instagram feed at the top it refreshes it, and new posts show up. That's the user experience I'm looking for, only in my case it is a "finite scroll", just with some div's hidden by default.
I currently have two implementations of it, neither fully achieves the desired experience. Both used jQuery Slim.
In both implementations, #hidden is the id of my hidden-by-default div, it has style="display: none;" inline, on the div tag.
The first one looks like this:
$(window).scroll(function() {
var x = $(document).height() - $(window).height() - 20;
if( $(window).scrollTop() > x ) {
$("#hidden").delay(1000).show(0);
}
else {
$("#hidden").hide(0);
}
});
The problem with this one is that when the div shows up it changes the document height, so when you get to the bottom of the page it kind of flickers (due to recomputing the document height), and sometimes goes back to being hidden. Really bad user experience.
The second one looks like this:
$(window).scroll(function() {
if( $(window).scrollTop() > 75 ) {
$("#hidden").delay(1000).show(0);
}
else {
$("#hidden").hide(0);
}
});
This one got rid of the flickering problem by keeping the threshold static altogether, slightly better user experience, but not really flexible, in the case that my page gets longer I'll have to set a new threshold for the div to show up.
In neither of the above solutions did the delay(1000) work. The div showed up as soon as the page gets scrolled to the bottom.
Is it possible to make this design work out?
You can try this code:
$(window).on("scroll", function() {
var scrollHeight = $(document).height();
var scrollPosition = $(window).height() + $(window).scrollTop();
if ((scrollHeight - scrollPosition) / scrollHeight === 0) {
$("#hidden").delay(1000).show(0);
}
});

Jquery change div based on another div's position

Let me start of by saying, I'm just now learning JS and Jquery, so my knowledge is very limited.
I've been looking around for 2 days now, and tried all sorts of combinations. But I just can't get this to work.
Below is an example of the layout
I'm looking for a way to trigger an event when div 1 is X px from the top of the screen. Or when div 1 collides with div 2.
What I'm trying to accomplish is to change the css of div 2 (the fixed menu) when div 1 is (in this case) 100px from the top of screen (browser window). Alternatively, when div1 passes div2 (I'm using responsive design, so the fixed height from top might become a problem on smaller screens right? Seeing as the header for example won't be there on a hand held.). So maybe collision detection is better here? Would really appreciate some thoughts and input on this matter.
Another issue is, div2 has to revert back to is previous css once div1 passes it (going back (beyond the 100px)).
This is what I have but it has no effect
$(document).ready(function() {
var content = $('#div1');
var top = $('#div2');
$(window).on('scroll', function() {
if(content.offset().top <= 100) {
top.css({'opacity': 0.8});
}else{
top.css({'opacity': 1});
}
});
});
I am not sure of the reason but $("#content").offset().top was giving a constant value on console. So I added window.scrollTOp() to check its distance from top, here is how it works,
$(document).ready(function() {
var top = $("#menu");
$(window).on('scroll', function(){
if(($('#content').offset().top - $(window).scrollTop()) <= 100){
top.css({'opacity': 0.4});
}else{
top.css({'opacity': 1});
}
});
});
And DEMO JSFIDDLE....

Make a div appear when scrolling past a certain point of a page

My goal is to make a fixed div appear at the top of a page once someone scrolls a certain amount of pixels down the page. Basically once the header section is out of view, this div will appear.
I've looked at code similar to what I want; however, haven't seen anything that would allow me to easily modify the pixel count from the top of the page (if possible).
Here is a piece of code I saw dealing with making divs appear by scrolling.
// Get the headers position from the top of the page, plus its own height
var startY = $('header').position().top + $('header').outerHeight();
$(window).scroll(function(){
checkY();
});
function checkY(){
if( $(window).scrollTop() > startY ){
$('.fixedDiv').slideDown();
}else{
$('.fixedDiv').slideUp();
}
}
// Do this on load just in case the user starts half way down the page
checkY();
I just want to know how to make it appear. If someone knows of a piece of code already in tact with a slide up and slide down animation, that would be greatly appreciated as well but not required.
window.addEventListener("scroll",function() {
if(window.scrollY > 500) {
$('.fixedDiv').slideDown();
}
else {
$('.fixedDiv').slideUp();
}
},false);
Brandon Tilley answered my question in a comment...
You would change the first line, with the startY, to be the specific Y
position you need, rather than calculating based on the header's
position and height. Here's an updated fiddle:
jsfiddle.net/BinaryMuse/Ehney/1
window.addEventListener("scroll",function() {
$('.fixedDiv')[(window.scrollY > 500)?"slideDown":"slideUp"]();
},false);
DEMO: http://jsfiddle.net/DerekL/8eG2A/

Solving scrolling element inside below div (under screen) - I want to have it fixed after scrolling

I do not know how to solve this situation:
I`ve got the html/css looks like this:
Image showing how my css/html looks like and what is displayed on the screen after landing on page:
The when I scroll down I see green element:
scrolling down ->
After continuing to scrolling down I saw full green element and the if I scroll down I want to have this element like in css language: position fixed bottom 0. See image below:
I ve saw full element -> same link but image called problem3.png
and then I scroll below and I want to have it fixed at the bottom of the page, like on this image:
Fixed element on screen - What I want and I do not know how to do that -> same link but image called problem4.png (stupid spam prevention mechanism)
Is it possible to solve this situation ?
To sum up: I`ve got two divs, one above and second below, Wheen I scroll down I suddenly see another element (green div) and when i continue to scroll down I WANT TO HAVE THIS GREEN DIV FIXED AT THE BOTTOM OF THE PAGE.
Ofcourse, when I scroll up (back on the top) I want to "park" that green div at the top of the second div.
Is there any way to solve this situation with jQuery (Javascript) / html / css ?
Thank you in advance
I think you'll have to show some of your html structure. There are lots of ways to achieve this kind of effect. Fundamentally, in javascript terms you'll be looking to:
Add an event listener to the window scroll that checks whether the green element is fully in view
If it is in view, add a class (or change it's css) that fixes it's position where you want
Change your window scroll method so that it's checking the relative offset of the red div to the top of the screen. If it goes below the position where the green div should be fixed, remove the class you added earlier.
That sounds complicated, but it's not too bad. The javascript would be something like:
$(function() {
$(window).scroll(function() {
if($(".divToFix").hasClass("fixedAtBase")){
if(Utils.underView($(".redDiv"), $(".divToFix").height())) $(".divToFix").removeClass("fixedAtBase");
} else {
if(Utils.inView($(".divToFix"))) $(".divToFix").addClass("fixedAtBase");
}
});
});
Utils = {
underView: function(element, offset) {
return (($(window).height() + $(window).scrollTop() - offset) <= element.offset().top);
},
aboveView: function(element) {
return ($(window).scrollTop() >= element.offset().top + element.height());
},
inView: function(element) {
return (Utils.aboveView(element) !== true && Utils.underView(element, element.height()) !== true);
}
};
Bear in mind I've not tested that or anything.
edit - here's a demo

Categories