Perform action when object is visible in viewport - javascript

I have a div on my page, and I would like the background color to change when the viewer scrolls down to it.
How can I do this?

I would have used CSS3 with something like this...
var elemTop = $('div').offset().top;
$(window).scroll(function() {
if($(this).scrollTop() == elemTop) {
$('div').removeClass('hidden');
}
});

The commenter above is right. You should try something first and when you get stuck, the community will help you get unstuck. That said, here's a quick jquery to solve your problem.
$(document).ready(function(){
var offsetTop = $('#test').offset().top, //offset from top of element - element has id of 'test'
finalOffset = offsetTop - document.documentElement.clientHeight; //screen size
$(window).on('scroll',function(){
var whereAmI = $(document).scrollTop();
if(whereAmI >= offsetTop){
console.log("i've arrived at the destination");
}
})
})
Note that the above code executes the console.log() at every point past your requirement (meaning from there downwards). In case you want the execution to happen only one, you need to adapt the code a bit. One more note - if you're checking this in a fiddle, this document.documentElement.clientHeight needs to be adapted to work in an iframe. So test it on your local machine.

Related

Check scrollpoint each pixel is scrolled

I need your help again. A try to code something like this:
I got an imaginary point on screen in pixel (lets say half of body) and I got a element in body. I want to alert if the elements TOP hits the imaginary line and alert if the elements bottom leave imaginary line.
I got something to work (for hit the line) but it only works a few times, but if I scroll fast it doesn't work. If I scroll very very slow and exactly the alert appears:
$(window).scroll(function () {
// A POINT I SET On SCREEN --> IN THIS CASE HALF SIZE OF BODY
var halfBody = $("body").height() / 2;
if ($(window).scrollTop() == halfBody) alert('HIER');
});
I think the problem is the exact pixels i try to match. I think with scrolling I haven't always the exact pixels.
How can this be done so that elements top cross the line alert('element top hits the line') and elements bottom leave the line alert('no element leaving the line'); ?
I hope you understand :)
Scroll events are trigger happy and handing each even can overwhelm your handler.
Try using lodash/underscore debnounce/threshould to handle them every X milliseconds.
It's a common practice to scroll handling in browsers.
Ok i found a nice solution with caching variables and a set timeout:
var timer;
var windowHeight = $(window).height();
var triggerHeight = 0.5 * windowHeight;
$(window).scroll(function() {
if(timer) {
window.clearTimeout(timer);
}
timer = window.setTimeout(function() {
// this variable changes between callbacks, so we can't cache it
var y = $(window).scrollTop() ;
if(y > triggerHeight) {
}
if( $(window).scrollTop() == 0 ) { // IF HITS TOP OF PAGE
}
}, 10);
});
maybe it helps someone!

Fly-in Fly-out effect on scroll jquery css animation

I am trying to make the elements on my site fly-in and fly-out on scroll.
This is the effect I am looking for.
http://nizoapp.com/
The effect in the nizo site is done with jquery, I think
I have tried many different ways to get this effect working, with Skrollr, scrollorama, and jquery animate and with css transitions etc etc etc
I decided to use css transitions as mad by the "css animation cheat sheet" (google it)
After a lot of effort and some borrowed code, I have got it half working, as in, I can get the elements to fly-in on down scroll, but not to fly back out on up scroll.
This is a jsfiddle with it half working
http://jsfiddle.net/mrcharis/Hjx3Z/4/
The code is......
function isScrolledIntoView(elem) {
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop + $(window).height();
var elemTop = $(elem).offset().top;
return ((elemTop <= docViewBottom) && (elemTop >= docViewTop));
}
$(window).scroll(function () {
$('.box').each(function (i) {
if (isScrolledIntoView(this)) {
$(this).addClass("slideRight");
}
});
});
// this is the function to check if is scroll down or up, but I cannot get it to trigger the fly in effect,
(function () {
var previousScroll = 0;
$(window).scroll(function () {
var currentScroll = $(this).scrollTop();
if (currentScroll > previousScroll){
// i figure to put the fly-in code here
}
else {
// and the fly-out code here
}
previousScroll = currentScroll;
});
}());
I have tried using another function (code chunk) to check if the scrolling is down or up, but i can't get it working with the existing code.
Any help to get this working would be awesome
Have a nice day
I will post the solution one day, if I can figure it out, sure someone else would like to know
The trick to knowing whether you're scrolling up or down is not to ask. Make it relational by using the top offset of the elements in question. Then it's as easy as > or <, for the most part.
Though if you do want to get the current direction you could always record the last scroll position and compare it with the current one.
var before = 0;
$(window).scroll(function(event){
var now = $(this).scrollTop();
if (now > before){
//on down code
} else {
//on up code
}
before = now;
});
Like the answer here suggests.
I like to trigger the events based on the screen size and the element position in the screen, so it doesn't matter whether it's up or down, it follows the same rules forwards and backwards. That way instead of asking up or down, it just asks if it's scrolling and executes it accordingly.
If you need me to make changes to my fiddle for you, just let me know what you want to happen. I only made the fiddle because of the horrible job they did on the tympanus.net example. You don't make a tutorial to accomplish a simple task 2 pages of js, that's unnecessary and it doesn't provide any instruction other than "hey, you want to do this? Then copy and paste these things I put together that have no clear course of action, and way too much code to digest quickly". Which doesn't help anyone learn.
After some code borrowing from tympanus.net and using the modernizer library I came up with this.
I tried different approaches as well but all of them turned out to have some flaws in them so I find best approach to be using the sample code and the already provided modernizer JS library.

Test if element can be seen by the user on an html page

Is there any way to know if an element is visible on an html page?
Like this:
One can probably do it considering the horizontal/vertical scrolling positions, the width/height of the browser window and the position/size of the element on the page, but I have little experience in jQuery so I don't know how to do it. And there might be a simple function one can call, I don't know.
You can use the .is(':visible') selectors to check if an element is currently visible in the DOM.
Edit:
However, as #BenM mentioned, this doesn't check if the elements on your page are actually out of your scrollable range - a great little plugin you could use in that case would be Viewport Selectors for jQuery.
Here is some code that I use to do this. It has been tested to work great.
function isVisible($obj) {
var top = $(window).scrollTop();
var bottom = top + $(window).height();
var objTop = $obj.offset().top;
var objBottom = objTop + $obj.height();
if(objTop < bottom && objBottom > top) {
//some part of $obj is visible on the screen.
//does not consider left/right, only vertical.
}
}

Calculating end of scroll on a web page

I need to calculate the end of scrolling on web page so that i can make an Ajax call.
I have searched posts in stackoverflow, but the solutions didn't worked for me.
I am using the below code ion order to determine that:
$(window).scrollTop() == $(document).height() - $(window).height()
but the above condition fails and am not able to get to know when page scroll ends.
As the values don't match on L.H.S and R.H.S the condition fails.
Just in order to check i used:
$(window).scrollTop() == $(document).height() - $(window).height() - 13
which works for chrome and firefox but fails for IE.
I need a concrete solution and don't want to hard code values.
Please help me in getting it right.
EDIT: To be specific, i am trying to calculate the end of vertical scroll bar.
Here is what I would do:
$(window).on('scroll', function() {
if($(window).scrollTop() != 0)
{
if( $(window).height() + $(window).scrollTop() >= $(document).height() )
{
//YES, I AM EXACTLY AT THE END OF THE SCROLL, PLZ FIRE AJAX NOW
}
}
});
CAUTION: Be very careful about having negative top margins though for styles in any of your elements on the page!! it may offset the calculation!
to calculate the end of scroll, try scrollHeight property.
This should retrieve the page height for you (not using jQuery but javascript instead):
var height = document.body.clientHeight;
You will find that this is the best cross-browser solution to your problem.
Here's how you do it. You take the scrolled distance and add the window height, then check if they equal the document height :
$(window).on('scroll', function() {
if (($(this).scrollTop() + $(this).height()) - $(document).outerHeight(true) >= 0) {
alert('Scrolled to bottom');
}
});
FIDDLE
This works for me in all five browsers!

change div based on how far down the page you have scrolled

I am trying to change the text inside a div based on how far down a page you have scrolled. I've been tinkering with jQuery's scrollTop and document height but have so far failed to produce the desired results.
How would I get the position of an element on the page and then get jQuery to do something once you have scrolled to that elements position?
Help is much appreciated!
There was a question on Stackoverflow that asked something similar and I whipped up a small example to illustrate how to accomplish this. I can't find the question right now, but here is the example. In this example there is a div that is shown until you scroll to a certain element in the page at which point the div is hidden. You can change this to achieve what you want, as the idea is the same. Here is the code modified for what you need:
$(document).ready(function() {
function isScrolledIntoView(elem) {
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop + $(window).height();
var elemTop = $(elem).offset().top;
var elemBottom = elemTop + $(elem).height();
return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom));
}
var myelement = $('#formcontainer'); // the element to act on if viewable
$(window).scroll(function() {
if(isScrolledIntoView(myelement)) {
// do something when element is scrolled to and viewable
} else {
// do something when element is not viewable
}
});
});
Good old ppk from quirksmode.org can show you how to find the position of an element: "This script finds the real position, so if you resize the page and run the script again, it points to the correct new position of the element."

Categories

Resources