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."
Related
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.
I am working on a website which uses snap.js and chart.js.
DEMO JSFIDDLE
After adding JavaScript to display the content from chart.js while user scroll, seems like it is in some trouble with the following style:
Line 10 - CSS: overflow: auto;
If I delete this style it works perfectly:
DEMO2 JSFIDDLE (without overflow)
The issue is that your window is no longer scrolling. Instead your .snap-content is. So you'll need to change the scroll handler to that element. You will then also have to modify your calculation a bit to work with this new setup:
http://jsfiddle.net/MU9aw/27/
function isScrolledIntoView(elem) {
var docViewTop = 0;
var docViewBottom = $(".snap-content").height();
var elemTop = $(elem).offset().top;
var elemBottom = elemTop + $(elem).height();
return ((elemTop <= docViewBottom) && (elemBottom >= docViewTop));
}
$(".snap-content").scroll(function () {
/* ... */
Note that your calculations will get considerably more complicated if your scrolling box does not fill the entire screen as you will need to determine if the element is visible within its box as well as that portion of the box being visible on the screen.
It's not the overflow that makes the issue.. It's the
.snap-content {
position: absolute; }
makes the issue. When I removed it, it works!
The problem is
$(window).scroll(function() {});
Doesn't fire when I scrolled maybe because since the element is absolute it keeps the original position in the screen without changing it. Make it to relative, and it will work.
I want to create a div containing endless scrollable content in a page.
For recognizing the end of the scrollable content in order to load more data from the data base I've written the following:
$(window).scroll(function(){
var wintop = $(window).scrollTop(), docheight = $(document).height(), winheight = $(window).height();
var scrolltrigger = 0.95;
if ((wintop/(docheight-winheight)) > scrolltrigger) {
lastAddedLiveFunc();
}
});
Question: The following code is for creating the endless scroll which fits in the entire webpage, but how can I write the same for a 'div' inside a web page?
(Hint: An exact similar thing is the Ticker on Facebook, on the right side which shows the recent activities of your friends in real time.)
The principle is the exact same. The div will be your browser viewport, and the div content is your document. You just need to exchange
$(window).scroll() --> $("#someDiv").scroll()
$(window).scrollTop() --> $("#someDiv").scrollTop()
$(document).height() --> $("#someDiv")[0].scrollHeight
$(window).height() --> $("#someDiv").height()
and it should work.
Note that:
scrollHeight is a property, not a function.
scrollHeight isn't jQuery, so you need to obtain it from the actual javascript element of the selector, hence the [0] addition. Another way is to use $("#someDiv").prop("scrollHeight").
$("#yourdiv").scroll(function(){
//your logic
}
You can use your div instead of window
For example
$('#yourdiv').scrollTop() // etc
use this
// get box div position
var box = document.getElementById('box').offsetTop;
window.onscroll = function(){
// get current scroll position
var scroll_top = document.body.scrollTop || document.documentElement.scrollTop;
document.getElementById('scbox').innerText = scroll_top + ' ' + box;
// if current scroll position >= box div position then box position fixed
if(scroll_top >= box)
document.getElementById('box').style.position = 'fixed';
else
document.getElementById('box').style.position = 'relative';
}
I´m using FullSlider.js to create a full-slide-webpage. In case the red element is fully visible, I need the browser to block the scroll event (means: window is not moving, but I´m able to receive the action) and than after I did some stuff I want to enable scrolling again.
That is what I did so far:
I read a lot of stuff about this and tried even more solutions like:
stop scrolling:
1. stop scrolling of webpage with jquery does not work at all
How to programmatically disable page scrolling with jQuery does stop the scrolling, but it is not possible to enable scrolling again
event prevent default, works fine in chrome, but less fine in firefox
check if element is visible:
Check if element is visible after scrolling
I used the solution above and tried:
to check if the red element is visible (did not work)
checked if a tiny span above the red element is visible (did not work well)
checked if a tiny span below the red element is visible (did not work well)
checked if a tiny span above and below the element is visible (did not work at all)
tried some idea about getting the scrollTop of the red element and check if the bodys scrollTop is equal or near
In fact the 2. solution did work quiet well, but I just was not able to figure out the offset I needed to at to compensate the "fixed-header navigation".
Currently I´m using the "isScrolledIntoView" to detect whether the position fits (works well on large screens, does not work at all on small screens). For the stop scrolling, I´m using the following hack:
CSS:
.scrollHack { position: static; overflow: hidden; }
JS:
$(document).on('mousewheel', function(event, delta) {
// stopScroll and isStopped are booleans delivered by another script
if(isScrolledIntoView($("#s3")))
{
isStopped = false;
if(delta >= 0) {
$('#s3').get(0).contentWindow.car.next(); // car.next();
}
else{
$('#s3').get(0).contentWindow.car.previous();
}
stopScroll = $('#s3').get(0).contentWindow.isStopped;
}
if(!stopScroll && isScrolledIntoView($("#s3")))
{
event.preventDefault();
$("body").addClass("scrollHack");
}
else
{
$("body").removeClass("scrollHack");
}
});
function isScrolledIntoView(elem)
{
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop + $(window).height();
var elemTop = $(elem).offset().top;
var elemBottom = elemTop + $(elem).height();
return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}
Was someone faced with an familiar situation and has some scripts or hacks that would help me out?
Sorry, I can't answer in a comment yet. So this is only a partial answer, regarding the second part of your question.
For checking whether your element is fully in view:
Try using jQuery innerHeight() instead of height(). This gives you the element height without margins and borders.
Checking for a tiny span above the red element should not be necessary. Wouldn't that be equal to just checking whether the top of the red element is on the screen? You could do that like this:
function isScrolledIntoView(elem) {
var docViewTop = $(window).scrollTop();
var elemTop = $(elem).offset().top;
return (elemTop >= docViewTop));
}
But this is only checking whether the top of your element is visible!
You say that your current solution does not work well on small screens. Could it be that the element you are checking is taller than the viewport on small screens?
Maybe this helps a little. Else it would be really good to see an example page or a jsfiddle example.
How does one locate the nearest HTML fragment identifier (hashtag href) based on window's current scroll position?
I want to make a bookmarking feature via JS/jQuery that captures the nearest section the user was in when hitting the bookmark button. I don't have access to the backend, so I can't add any hooks/hidden fields, but that shouldn't matter because the fragment IDs are my hooks.
I'm thinking jQuery's .scroll() handler could be of use, but I'm not sure how to locate the "DOM content at a given scroll position" to know if a new identifier has appeared. Or if that's even the best approach...
Thoughts?
Something like that:
$('a [href]').filter(function() {
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop + $(window).height();
var elemTop = $(this).offset().top;
var elemBottom = elemTop + $(this).height();
return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
})
.first();
While not technically an answer to my original question, this is the more flexible solution I decided to use:
When the user hits "bookmark" jQuery will store the page url with a phantom query string tacked on of pos=X where X is the current value of $('body').scrollTop().
When a user wants to revisit his bookmark, the stored URL will be loaded and the inserted jQuery will retrieve the pos value and scroll the page to the bookmarked position.
This is ideal because it literally puts the user right back where he/she left off, down to the pixel.
i quite don't understand your question, but to do something on scroll using jquery you can try this.
$(document).ready(function(){
$(window).scroll(function(){
if ($(window).scrollTop() > 100){
/*you check if identifier has appeared here*/
}
});
});