I'm trying to figure how to trigger an jquery animation when the user scrolls to the middle of the page. Is there a way to set a listener to see if the person scrolls halfway down the page it activates the jquery code?
Using jQuery, you can attach an event handler to the scroll event, which will let you listen to whenever the window is scrolled and determine whether the user has scrolled the appropriate amount.
$(window).scroll(function () {
if (($(window).scrollTop()) > ($(document).height() / 2)) {
// Run animation here
}
});
http://jsfiddle.net/ult_combo/XdqPJ/1/
Think so.. you can look at checking parts of the page using;
setInterval(name_Of_Function,1000);
runs every second, then run a check on there is;
window.pageYOffset // Gives you current horizontal window scroll position for the page.
Firebug is helpful to get more information on these functions. Remember to check in all major browsers as the implementation or values returned may be slightly different between different browsers.
Good reference page I found;
http://www.softcomplex.com/docs/get_window_size_and_scrollbar_position.html
Is there a way to set a listener to see if the person scrolls halfway
down the page it activates the jquery code?
You can get the amount that the user has scrolled with the following:
$("html,body").scrollTop();
so, to trigger an event halfway down the page:
if (($("html,body").scrollTop()) > ($("html,body").height() / 2))
{
// Code that will be triggered
}
You would need a timer to constantly be checking this. You can use setInterval() in Javascript to repeatedly execute a function to check this.
http://api.jquery.com/scrollTop/
Related
What is the best-performance way to get window.scroll position when user scrolls the page?
Maybe when the event fires there is some variable witch natively store something like $(window).scrollTop() value and there is no need to call $(window).scrollTop() manually to figure it out?
You can access the scroll via the $(this) keyword.
So you'd do something like this:
$(window).on('scroll', function() {
var scroll = $(this)[0].scrollY
});
That's your alternative. I didn't do any tests to see whether it's better performance wise, but it's an option if you do not want to call the $(window).scrollTop()
Problem:
I Cannot get correct top offset value of DOM element when page just loaded.
The project I'm working on needs to get the offsetTop value of several DOM element when the page just loaded.
The reason is that I need to re-position several DOM element depends on the $window height and their initial position on the webpage.
If the DOM element is all the way down the page, I want to put a fixed bar on the bottom of the page to indicate the users "there's more, but you need to scroll down to see it".
Debugging Phase:
Method I have tried:
angular.element ready event and angular $viewContentLoaded event
Here is my snippet of code of getting the offsetTop of a element
angular.element(document).ready(function(){
var elem = angular.element(document.getElementById('test-element');
console.log(elem[0].getBoundingClientRect().top;
console.log(elem[0].offsetTop);
console.log(elem.offset().top);
});
and
$scope.$on('$viewContentLoaded', function(){
var elem = angular.element(document.getElementById('test-element');
console.log(elem[0].getBoundingClientRect().top;
console.log(elem[0].offsetTop);
console.log(elem.offset().top);
});
Above will all print wrong offsetTop of the element. Then I create a timeout function to test the offsetTop value of the same element, which yield the correct offset top.
$timeout(function(){
var elem = angular.element(document.getElementById('test-element');
console.log(elem[0].getBoundingClientRect().top;
console.log(elem[0].offsetTop);
console.log(elem.offset().top);
},100);
Basically, the timeout function waits 100ms to read the top offset of the same element, whic h gives me a correct offset
Assumption:
My assumptions why this happens because:
I use ngRepeat to produce a table. The content of the table is fetched from database when the page loaded.
$viewContentLoaded and angular.element ready event fire before the ngRepeat render its content. That's a possible reason because when fetching offset in $viewContentLoaded/ready event function, it has no idea of the height/offset the "ngRepeat" table yet.
The reason why $timeout function can get the correct top offset is that when the $timeout function execute its code, ngRepeat finishes its work and everything on the webpage is on stable state.
There exists a timing between $timeout function and $viewContentLoaded/ready event that will give me correct offset value.
Questions:
Is the assumption about ngRepeat/$viewContentLoaded/ready correct?
What's the right way to fetch the top offset for a DOM element when the page just loaded?
Or, what's the right event to fetch the correct offset?
It's a long description of the problem. I hope I made it clear. I'm sorry for any English syntax error.
Thank you a lot.
You should probably fire an event for your ngrepeat's finish, like this:
https://stackoverflow.com/a/15208347/4497117
Then you could catch that exact event in your directive.
This is the closest i have seen to be working (without too much clutter).
Also be aware that if you have visibility toggling (ng-show) at the moment the custom ngrepeat finish event fires, you may still get weird values
Answering #2:
getBoundingClientRect() is relative to the current scroll position and will change as the page scrolls. Hence, to see if an element is outside the current viewport, you could do something like this:
function isOffscreen(el) {
var rect = el.getBoundingClientRect();
return (rect.bottom > 0 || rect.bottom <= window.innerHeight);
}
I'm trying to execute a Javascript function whenever a user scrolls a page.
I've tried:
<body onscroll="myScrollFunction()">
and this works fine in Firefox but not IE.
I also tried:
window.onscroll = "myScrollFunction()";
but this seems to only perform the function once, similar to an onload event, but further scrolls do not fire the event. My doctype is set to strict; not sure if this makes a difference or not.
How can I get this to work across all browsers?
What I'm trying to accomplish is a way to prevent users from scrolling once a modal is displayed. I'd rather not use
overflow:hidden
because the document shifts slightly when the modal is displayed (to compensate for the scrollbar), so I figured I could capture the scroll function and lock it to the top of the page whenever the modal is displayed. If there is an easier way to do this, please let me know.
Instead of
window.onscroll = myScrollFunction();
which assigns the result of the myScrollFunction() to the onscroll handler, you want
window.onscroll = myScrollFunction;
which assigns the function itself, and will therefore be called on each scroll.
I suggest that instead of doing that, you just give your modal dialog position: fixed; which will fix it to the viewport instead of the page.
Set the <body>'s overflow to hidden while your lightbox is open.
$('body').css('overflow','hidden');
...then return to normal when it closes:
$('body').css('overflow','auto');
I have a page in which the user clicks one link to start scrolling down the page automatically for ease in reading. There is another link the user clicks to stop the scrolling. The former works perfectly, but the latter makes the page jump back to the top when clicked instead of stopping the scrolling at the that place on the page. Any ideas?
function pageScroll() {
window.scrollBy(0,1); // horizontal and vertical scroll increments
scrolldelay = setTimeout('pageScroll()',50); // scrolls every 100 milliseconds
}
function stopScroll() {
clearTimeout(scrolldelay);
}
I tried to add return false; to the second function from something I read on another post, but it didn't help. I don't fully understand the use of return anyhow. Thanks for any help.
I assume that you're doing something like this:
start
stop
The quickest fix is to return false from the onclick event handlers, like this:
start
stop
The idea is to stop the browser from doing the default action of the event (in this case, going to #, which scrolls to the top of the page). Nowadays, the more modern way is to bind an event handler function, then use e.preventDefault() in it, but return false; still works for old-style event attributes.
I'm trying to trigger a function when the window is scrolled more than a certain number of pixels.
Here's my code:
$(window).scroll(function(){
if( $(this).scrollTop() >= 100 ) {
someFunction();
} else {
someOtherFunction();
}
});
It kinda works, but there's either a delay of around 2-4 seconds after scrolling before the function(s) are fired or else the functions aren't triggered at all.
Tried it out in Safari / Chrome. Don't know if that helps or not!
The code looks fine and works for me.
As Wolfram says, it's rarely a good idea to attach handlers directly to the scroll event, as this fires a lot and can bring the user's system to a crawl.
I'd recommend using Ben Alman's jquery throttle/debounce plugin.
It works using jQuery 1.6.1 + mousewheel / scrollbar in Chrome15/Safari5.1/FF7 on OSX. What are you doing in those two functions? For testing, I put a simple alert() in someFunction and nothing in someOtherFunction.
Remember that one of those functions is executed every time the scroll-event fires unless you stop it once it was called... e.g. someFunction is called a lot after you scrolled below the 100px line.
John Resig: It's a very, very, bad idea to attach handlers to the window scroll event.
If you're scolling by holding in the click-button instead of using the scroll wheel, I believe the event won't fire until you release the click-button.
Have you considered running a loop that checks the scrollTop instead?
EDIT:
I just check an old project of mine using window scroll event, and it runs perfect with the same event.
I asume you have this script of yours wrapped inside:
$(function() {
// code
});