My animation event nearly pauses or lets say gets significantly slower at completing when scroll reaches more than 15 percent. Why is that? If should animate to the left but instead it does so only when I stop scrolling.
$(window).scroll(function ()
{
var content_height = $(document).height();
var content_scroll_pos = $(window).scrollTop();
var percentage_value = content_scroll_pos * 100 / content_height;
if(percentage_value > 15)
{
TweenMax.to(".bar", 3, {right:"0", ease:Bounce.easeOut})
}
else
{
TweenMax.to(".bar", 2, {right:"-125%", ease:Power2.easeOut})
}
});
Here a Demo of the solution with explaining comments:
// This gets called _every time_, you scroll a little bit ("every time" as in "every frame").
// So we introduce a new variable that acts as a filter and only lets the function trigger, once the status changes.
// 0 = not changed (it is, where it was on page loading)
// 1 = out of the screen
// 2 = back in the screen
var status = 0;
$(window).scroll(function ()
{
var content_height = $(document).height();
var content_scroll_pos = $(window).scrollTop();
var percentage_value = content_scroll_pos * 100 / content_height;
var newStatus = percentage_value > 15 ? 2 : 1;
if(newStatus == status)
return;
switch(newStatus) {
case 1:
TweenMax.to(".bar", 2, {right:"-125%", ease:Power2.easeOut});
break;
case 2:
// because this function got called all the time, the animation started all over again, each frame.
// And becase the animation starts slowly it stayed slow as long as the user scrolled.
TweenMax.to(".bar", 3, {right:"0", ease:Bounce.easeOut});
break;
}
status = newStatus;
});
.foo {
height: 2000px;
}
.bar {
background-color: red;
height: 50px;
width: 50px;
position: fixed;
}
<script src="http://cdnjs.cloudflare.com/ajax/libs/gsap/latest/TweenMax.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="foo">
Test<br />
Test
<div class="bar">
</div>
</div>
By the way:
Because of the nasty per-frame thing, you can improve your performance significantly, if you do not calculate the value of $(document), $(document).height() and $(window) inside that function. I would suggest, scoping all of this code in a wrap like
(function() {
var jDocument = $(document),
content_height = jDocument.height(),
jWindow = $(window),
status = 0;
// [CODE HERE, using jWindow instead of $(window)]
})();
Which also solves the problem, that status would either need a long and complicated name otherwise or would be in danger of getting overwritten by the code of anybody else.
PS: I have to admit, that I don't like your animation in the current state. It bounces too much for me - even that much too much, that I can not see it bouncing at all. To me it seemed like it appeared and disappeared, the first time, I saw it.
Related
I have a fixed-positioned full-screen image gallery. The container div height is set via jQuery, and the next div (#page) has a margin-top equal to window.height.
Here is this code:
var windowH = $(window).height();
var windowW = $(window).width();
function marginTop() {
var currentH = $(window).height();
$("#page").css("margin-top", currentH +'px');
$("#image-gallery").css("height", currentH +'px');
console.log('mTop fired!');
};
$(window).resize(function() {
var newH = $(window).height(); // Records new windows height after resize
var newW = $(window).width();
var maxH = windowH + 90; // Sets a positive delta of some px
var maxW = windowW + 60;
var minH = windowH - 90; // Sets a negative delta of some px
var minW = windowW - 60;
if(newH > maxH) { // If the height difference is more than 50px, then set new marginTop for #page
marginTop();
console.log('fire for bigger height');
} else if(newH < minH) {
marginTop();
console.log('fire for smaller height');
} else if(newW > maxW) {
marginTop();
console.log('fire for bigger width');
} else if(newW < minW ) {
marginTop();
console.log('fire for smaller width');
}
});
I've split the conditions in several else if statement because it didn't work fine, and I had to check out when it was working, when not.
The various if...elseif...elseif... solve a problem on mobile browsers: without that delta, the #image-gallery div would change dimension when the address bar appears or disappears, resulting in stuttering adjustments of the div's height. Moreover, i did not want to redraw the whole thing for small changes in viewport on desktop too.
However it has some problem, as it doesn't work correctly. In particular:
marginTop() is fired only for window.resize with smaller height (checked from console.log)
on desktop, if the window is resized through the top-right-corner button, it doesn't fire at all.
removing all the if-else-if conditions, it works fine on desktop in any situation (but the address-bar is still a problem on mobile)
Can't figure it out, the code seems fine to me, but not to browsers. Where's the catch?
Tested on Firefox and Chrome latest
There's a host of small problems here. Your if statement, as is, will never reach the width compares. First of all, with the width being in a if else with the height, then height is always evaluated first and width is never hit if height is adjusted.
Next, your "current height|width" as seen at var windowH = $(window).height(); is never reset. This means, if the user show up with a viewport (say browser is minimized) of 200:150, then height:width will always be measured based on 200:150. This would make for a very different experience from someone using a much larger viewport.
Another issue, often found with window re-sizing, is the multiple amount of times your code will fire. This can cause major issue with overlapping commands, thus causing double feedback.
Below is how I would handle this and a suggested rebuild.
/* simple method to get the current window size as an object where h=height && w=width */
function getWindowSize() {
return { h: $(window).height(), w: $(window).width() };
}
function doWork(typ, msg) {
// report msg of change to console
console.log(typ == 'h' ? 'HEIGHT:\t' : 'WIDTH:\t', msg);
// we really only need fire your method if height has changed
if (typ == 'h') marginTop();
// a change was made, now to reset
window.sizeCheck = getWindowSize();
}
// your original method
// brokered off so it can be used independently
function marginTop() {
var currentH = $(window).height();
console.log('currentH', currentH)
$("#page").css("margin-top", currentH +'px');
$("#image-gallery, #page").height(currentH);
console.log('mTop fired!');
}
/* action area for window resize event */
function windowResize() {
// made my variables short and sweet,
// sch=sizeCheck, scu=sizeCurrent
var sch = window.sizeCheck, // get previously set size
scu = getWindowSize(),
maxH = sch.h + 90,
minH = sch.h - 90,
maxW = sch.w + 60,
minW = sch.w - 60;
if (scu.h > maxH) doWork('h', 'View Got <b>Taller</b>');
else if (scu.h < minH) doWork('h', 'View Got <i>shorteR</i>');
// for what you want, the following isn't even really nec
// but i'll leave it in so you can see the work
if (scu.w > maxW) doWork('w', 'View Got <b>Wider</b>');
else if (scu.w < minW) doWork('w', 'View Got <i>thinneR</i>');
}
$(function() {
// ezier to maintain one global variable than to scope
// shot 2 which could easily be overriden in a latter method,
// by simple confusion
window.sizeCheck = getWindowSize();
// call of event to establish correct margin for the page div
marginTop()
$(window).resize(function(e) {
// this will clear our timer everytime resize is called
if (this.tmrResize) clearTimeout(this.tmrResize);
// resize is called multiple times per second,
// this helps to seperate the call,
// and ensure a little time gap (1/4 second here)
this.tmrResize = setTimeout(windowResize, 250);
});
})
html, body { margin: 0; padding: 0; }
#image-gallery {
background: blue;
color: white;
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
#page { background: white; color: red; height: 400px; position: relative; z-index: 1; }
p { padding: 3em; text-align: center; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="image-gallery">
<p>
image Gallery
</p>
</div>
<div id="page">
<p>
next page
</p>
</div>
Someone passed by and then voted -1 to my question. I'd just like to know who's the braveheart that judges others without even posting a simple comment. This behaviour should be forbidden, we're not on 9gag neither 4chan.
I have this event:
$(window).scroll(function(e){
console.log(e);
})
I want to know, how much I have scroll value in pixels, because I think, scroll value depends from window size and screen resolution.
Function parameter e does not contains this information.
I can store $(window).scrollTop() after every scroll and calculate difference, but can I do it differently?
The "scroll value" does not depend on the window size or screen resolution. The "scroll value" is simply the number of pixels scrolled.
However, whether you are able to scroll at all, and the amount you can scroll is based on available real estate for the container and the dimensions of the content within the container (in this case the container is document.documentElement, or document.body for older browsers).
You are correct that the scroll event does not contain this information. It does not provide a delta property to indicate the number of pixels scrolled. This is true for the native scroll event and the jQuery scroll event. This seems like it would be a useful feature to have, similar to how mousewheel events provide properties for X and Y delta.
I do not know, and will not speculate upon, why the powers-that-be did not provide a delta property for scroll, but that is out of scope for this question (feel free to post a separate question about this).
The method you are using of storing scrollTop in a variable and comparing it to the current scrollTop is the best (and only) method I have found. However, you can simplify this a bit by extending jQuery to provide a new custom event, per this article: http://learn.jquery.com/events/event-extensions/
Here is an example extension I created that works with window / document scrolling. It is a custom event called scrolldelta that automatically tracks the X and Y delta (as scrollLeftDelta and scrollTopDelta, respectively). I have not tried it with other elements; leaving this as exercise for the reader. This works in currrent versions of Chrome and Firefox. It uses the trick for getting the sum of document.documentElement.scrollTop and document.body.scrollTop to handle the bug where Chrome updates body.scrollTop instead of documentElement.scrollTop (IE and FF update documentElement.scrollTop; see https://code.google.com/p/chromium/issues/detail?id=2891).
JSFiddle demo: http://jsfiddle.net/tew9zxc1/
Runnable Snippet (scroll down and click Run code snippet):
// custom 'scrolldelta' event extends 'scroll' event
jQuery.event.special.scrolldelta = {
delegateType: "scroll",
bindType: "scroll",
handle: function (event) {
var handleObj = event.handleObj;
var targetData = jQuery.data(event.target);
var ret = null;
var elem = event.target;
var isDoc = elem === document;
var oldTop = targetData.top || 0;
var oldLeft = targetData.left || 0;
targetData.top = isDoc ? elem.documentElement.scrollTop + elem.body.scrollTop : elem.scrollTop;
targetData.left = isDoc ? elem.documentElement.scrollLeft + elem.body.scrollLeft : elem.scrollLeft;
event.scrollTopDelta = targetData.top - oldTop;
event.scrollTop = targetData.top;
event.scrollLeftDelta = targetData.left - oldLeft;
event.scrollLeft = targetData.left;
event.type = handleObj.origType;
ret = handleObj.handler.apply(this, arguments);
event.type = handleObj.type;
return ret;
}
};
// bind to custom 'scrolldelta' event
$(window).on('scrolldelta', function (e) {
var top = e.scrollTop;
var topDelta = e.scrollTopDelta;
var left = e.scrollLeft;
var leftDelta = e.scrollLeftDelta;
// do stuff with the above info; for now just display it to user
var feedbackText = 'scrollTop: ' + top.toString() + 'px (' + (topDelta >= 0 ? '+' : '') + topDelta.toString() + 'px), scrollLeft: ' + left.toString() + 'px (' + (leftDelta >= 0 ? '+' : '') + leftDelta.toString() + 'px)';
document.getElementById('feedback').innerHTML = feedbackText;
});
#content {
/* make window tall enough for vertical scroll */
height: 2000px;
/* make window wide enough for horizontal scroll */
width: 2000px;
/* visualization of scrollable content */
background-color: blue;
}
#feedback {
border:2px solid red;
padding: 4px;
color: black;
position: fixed;
top: 0;
height: 20px;
background-color: #fff;
font-family:'Segoe UI', 'Arial';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='feedback'>scrollTop: 0px, scrollLeft: 0px</div>
<div id='content'></div>
Note that you may want debounce the event depending on what you are doing. You didn't provide very much context in your question, but if you give a better example of what you are actually using this info for we can provide a better answer. (Please show more of your code, and how you are using the "scroll value").
To detemine how many pixels were scrolled you have to keep in mind that the scroll event gets fired almost every pixel that you move. The way to accomplish it is to save the previous scrolled value and compare that in a timeout. Like this:
var scrollValue = 0;
var scrollTimeout = false
$(window).scroll(function(event){
/* Clear it so the function only triggers when scroll events have stopped firing*/
clearTimeout(scrollTimeout);
/* Set it so it fires after a second, but gets cleared after a new triggered event*/
scrollTimeout = setTimeout(function(){
var scrolled = $(document).scrollTop() - scrollValue;
scrollValue = $(document).scrollTop();
alert("The value scrolled was " + scrolled);
}, 1000);
});
This way you will get the amount of scrolled a second after scrolling (this is adjustable but you have to keep in mind that the smooth scrolling that is so prevalent today has some run-out time and you dont want to trigger before a full stop).
The other way to do this? Yes, possible, with jQuery Mobile
I do not appreciate this solution, because it is necessary to include heavy jQuery mobile. Solution:
var diff, top = 0;
$(document).on("scrollstart",function () {
// event fired when scrolling is started
top = $(window).scrollTop();
});
$(document).on("scrollstop",function () {
// event fired when scrolling is stopped
diff = Math.abs($(window).scrollTop() - top);
});
To reduce the used processing power by adding a timer to a Jquery scroll method is probably not a great idea. The visual effect is indeed quite bad.
The whole web browsing experience could be made much better by hiding the scrolling element just when the scroll begins and making it slide in (at the right position) some time after. The scrolling even can be checked with a delay too.
This solution works great.
$(document).ready(function() {
var element = $('.movable_div'),
originalY = element.offset().top;
element.css('position', 'relative');
$(window).on('scroll', function(event) {
var scrollTop = $(window).scrollTop();
element.hide();
element.stop(false, false).animate({
top: scrollTop < originalY
? 0
: scrollTop - originalY + 35
}, 2000,function(){element.slideDown(500,"swing");});
});
});
Live demo here
I have an h1 that is far down a page..
<h1 id="scroll-to">TRIGGER EVENT WHEN SCROLLED TO.</h1>
and I want to trigger an alert when the user scrolls to the h1, or has it in it's browser's view.
$('#scroll-to').scroll(function() {
alert('you have scrolled to the h1!');
});
how do I do this?
You can calculate the offset of the element and then compare that with the scroll value like:
$(window).scroll(function() {
var hT = $('#scroll-to').offset().top,
hH = $('#scroll-to').outerHeight(),
wH = $(window).height(),
wS = $(this).scrollTop();
if (wS > (hT+hH-wH)){
console.log('H1 on the view!');
}
});
Check this Demo Fiddle
Updated Demo Fiddle no alert -- instead FadeIn() the element
Updated code to check if the element is inside the viewport or not. Thus this works whether you are scrolling up or down adding some rules to the if statement:
if (wS > (hT+hH-wH) && (hT > wS) && (wS+wH > hT+hH)){
//Do something
}
Demo Fiddle
Combining this question with the best answer from jQuery trigger action when a user scrolls past a certain part of the page
var element_position = $('#scroll-to').offset().top;
$(window).on('scroll', function() {
var y_scroll_pos = window.pageYOffset;
var scroll_pos_test = element_position;
if(y_scroll_pos > scroll_pos_test) {
//do stuff
}
});
UPDATE
I've improved the code so that it will trigger when the element is half way up the screen rather than at the very top. It will also trigger the code if the user hits the bottom of the screen and the function hasn't fired yet.
var element_position = $('#scroll-to').offset().top;
var screen_height = $(window).height();
var activation_offset = 0.5;//determines how far up the the page the element needs to be before triggering the function
var activation_point = element_position - (screen_height * activation_offset);
var max_scroll_height = $('body').height() - screen_height - 5;//-5 for a little bit of buffer
//Does something when user scrolls to it OR
//Does it when user has reached the bottom of the page and hasn't triggered the function yet
$(window).on('scroll', function() {
var y_scroll_pos = window.pageYOffset;
var element_in_view = y_scroll_pos > activation_point;
var has_reached_bottom_of_page = max_scroll_height <= y_scroll_pos && !element_in_view;
if(element_in_view || has_reached_bottom_of_page) {
//Do something
}
});
I think your best bet would be to leverage an existing library that does that very thing:
http://imakewebthings.com/waypoints/
You can add listeners to your elements that will fire off when your element hits the top of the viewport:
$('#scroll-to').waypoint(function() {
alert('you have scrolled to the h1!');
});
For an amazing demo of it in use:
http://tympanus.net/codrops/2013/07/16/on-scroll-header-effects/
Inview library triggered event and works well with jquery 1.8 and higher!
https://github.com/protonet/jquery.inview
$('div').on('inview', function (event, visible) {
if (visible == true) {
// element is now visible in the viewport
} else {
// element has gone out of viewport
}
});
Read this https://remysharp.com/2009/01/26/element-in-view-event-plugin
Fire scroll only once after a successful scroll
Note: By successful scroll I mean when the user has scrolled to the desired
element or in other words when the desired element is in view
The accepted answer worked 90% for me so I had to tweak it a little to actually fire only once.
$(window).on('scroll',function() {
var hT = $('#comment-box-section').offset().top,
hH = $('#comment-box-section').outerHeight(),
wH = $(window).height(),
wS = $(this).scrollTop();
if (wS > ((hT+hH-wH)-500)){
console.log('comment box section arrived! eh');
// This detaches the scroll so doStuff() won't run more than once
$(window).off('scroll');
doStuff();
}
});
You could use this for all devices,
$(document).on('scroll', function() {
if( $(this).scrollTop() >= $('#target_element').position().top ){
do_something();
}
});
Intersection Observer can be the best thing IMO, without any external library it does a really good job.
const options = {
root: null,
threshold: 0.25, // 0 - 1 this work as a trigger.
rootMargin: '150px'
};
const target = document.querySelector('h1#scroll-to');
const observer = new IntersectionObserver(
entries => { // each entry checks if the element is the view or not and if yes trigger the function accordingly
entries.forEach(() => {
alert('you have scrolled to the h1!')
});
}, options);
observer.observe(target);
You can use jQuery plugin with the inview event like this :
jQuery('.your-class-here').one('inview', function (event, visible) {
if (visible == true) {
//Enjoy !
}
});
Link : https://remysharp.com/2009/01/26/element-in-view-event-plugin
This should be what you need.
Javascript:
$(window).scroll(function() {
var hT = $('#circle').offset().top,
hH = $('#circle').outerHeight(),
wH = $(window).height(),
wS = $(this).scrollTop();
console.log((hT - wH), wS);
if (wS > (hT + hH - wH)) {
$('.count').each(function() {
$(this).prop('Counter', 0).animate({
Counter: $(this).text()
}, {
duration: 900,
easing: 'swing',
step: function(now) {
$(this).text(Math.ceil(now));
}
});
}); {
$('.count').removeClass('count').addClass('counted');
};
}
});
CSS:
#circle
{
width: 100px;
height: 100px;
background: blue;
-moz-border-radius: 50px;
-webkit-border-radius: 50px;
border-radius: 50px;
float:left;
margin:5px;
}
.count, .counted
{
line-height: 100px;
color:white;
margin-left:30px;
font-size:25px;
}
#talkbubble {
width: 120px;
height: 80px;
background: green;
position: relative;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
border-radius: 10px;
float:left;
margin:20px;
}
#talkbubble:before {
content:"";
position: absolute;
right: 100%;
top: 15px;
width: 0;
height: 0;
border-top: 13px solid transparent;
border-right: 20px solid green;
border-bottom: 13px solid transparent;
}
HTML:
<div id="talkbubble"><span class="count">145</span></div>
<div style="clear:both"></div>
<div id="talkbubble"><span class="count">145</span></div>
<div style="clear:both"></div>
<div id="circle"><span class="count">1234</span></div>
Check this bootply:
http://www.bootply.com/atin_agarwal2/cJBywxX5Qp
If you are looking for a javascript version. You can call this method on scroll event listener.
showScrollTop = () =>{
const currentScrollPosition = window.pageYOffset;
let elementID = 'service-selector'
const elementOffsetTop = document.getElementById(elementID).offsetTop
if ( currentScrollPosition > elementOffsetTop){
// place your logic here
} else {
// place your logic here
}
}
window.addEventListener('scroll', showScrollTop)
If you are doing a lot of functionality based on scroll position, Scroll magic (http://scrollmagic.io/) is built entirely for this purpose.
It makes it easy to trigger JS based on when the user reaches certain elements when scrolling. It also integrates with the GSAP animation engine (https://greensock.com/) which is great for parallax scrolling websites
Just a quick modification to DaniP's answer, for anyone dealing with elements that can sometimes extend beyond the bounds of the device's viewport.
Added just a slight conditional - In the case of elements that are bigger than the viewport, the element will be revealed once it's top half has completely filled the viewport.
function elementInView(el) {
// The vertical distance between the top of the page and the top of the element.
var elementOffset = $(el).offset().top;
// The height of the element, including padding and borders.
var elementOuterHeight = $(el).outerHeight();
// Height of the window without margins, padding, borders.
var windowHeight = $(window).height();
// The vertical distance between the top of the page and the top of the viewport.
var scrollOffset = $(this).scrollTop();
if (elementOuterHeight < windowHeight) {
// Element is smaller than viewport.
if (scrollOffset > (elementOffset + elementOuterHeight - windowHeight)) {
// Element is completely inside viewport, reveal the element!
return true;
}
} else {
// Element is larger than the viewport, handle visibility differently.
// Consider it visible as soon as it's top half has filled the viewport.
if (scrollOffset > elementOffset) {
// The top of the viewport has touched the top of the element, reveal the element!
return true;
}
}
return false;
}
I use the same code doing that all the time, so added a simple jquery plugin doing it.
480 bytes long, and fast. Only bound elements analyzed in runtime.
https://www.npmjs.com/package/jquery-on-scrolled-to
It will be
$('#scroll-to').onScrolledTo(0, function() {
alert('you have scrolled to the h1!');
});
or use 0.5 instead of 0 if need to alert when half of the h1 shown.
Quick and fast implementation,
let triggered = false;
$(window).on('scroll',function() {
if (window.scrollY > ($('#scrollTo').offset().top+$('#scrollTo').outerHeight()-window.innerHeight) & !triggered){
console.log('triggered here on scroll..');
triggered = true;
}
});
using global variable triggered = false makes it just to happen once, otherwise, every time crossing past the element, this action is triggered.
Here is My page,It is a demo to test moving a element,but after you change your page sometime,and back to here,why the DIV move faster?
My css:
#box1 {
width: 900px;
height: 50px;
background-color: #000;
position: relative;
}
#box2 {
width: 50px;
height: 50px;
background-color: #a00;
position: absolute;
}
My HTML:
<div id="box1">
<div id="box2"></div>
</div>
My Js:
var box2 = document.getElementById("box2");
var remove = setInterval(function () {
box2.style.left = "0px";
var move = setInterval(function () {
var newLeft = Math.min(parseInt(box2.style.left) + 5, 850) + "px";
box2.style.left = newLeft;
if (newLeft == "850px") clearInterval(move)
}, 20);
}, 5000)
The rate of setInterval cannot be trusted. A browser might not fire it when the tab is not focused, and as well might fire it more often than needed.
The behaviour is standardisized in the current HTML5 draft on the WindowTimers interface (which does not mean it was implemented like that). There you will find the note:
This API does not guarantee that timers will run exactly on schedule. Delays due to CPU load, other tasks, etc, are to be expected.
and, even more explicit:
9) Optionally, wait a further user-agent defined length of time.
Note: This is intended to allow user agents to pad timeouts as needed to optimise the power usage of the device. For example, some processors have a low-power mode where the granularity of timers is reduced; on such platforms, user agents can slow timers down to fit this schedule instead of requiring the processor to use the more accurate mode with its associated higher power usage.
You might also want to have a look at the WindowAnimationTiming draft.
And if you do use setInterval/setTimeout in animations/clocks/etc, always measure the really elapsed time with Date objects (e.g. via Date.now()).
Some browsers don't bother to fire timeout/interval events if the window is unfocused. When the window regains focus, it fires all of them at once. It's a performance decision (Why fire an event every millisecond if the user won't even notice?), and, to my knowledge, there's no way to change this behavior.
Mozilla Firefox and Google Chrome both throttle the speed of ticks that an interval when the tab is inactive (Sources: http://pivotallabs.com/users/mrushakoff/blog/articles/2035-chrome-and-firefox-throttle-settimeout-setinterval-in-inactive-tabs, https://stackoverflow.com/a/6032591/1756941)
And so, as this answer suggests, capture the date and check it against the tick, to verify if it's working correctly, else compensate for the missing time..
JS:
var tick = 20;
var newLeft=0;
var box2 = document.getElementById("box2");
var remove = setInterval(function() {
box2.style.left = "0px";
var now, before = new Date();
var move = setInterval(function() {
now = new Date();
var elapsedTime = (now.getTime() - before.getTime());
if (elapsedTime > tick) {
console.log((Math.floor(elapsedTime / tick) * 5));
newLeft = Math.min(parseInt(box2.style.left) + (Math.floor(elapsedTime / tick) * 5), 850) + "px";
}
else {
newLeft = Math.min(parseInt(box2.style.left) + 5, 850) + "px";
}
box2.style.left = newLeft;
before = new Date();
if (newLeft == "850px"){clearInterval(move);}
}, tick);
}, 5000);
JSFiddle: http://jsfiddle.net/3jY8h/1/
I'm using the following code to find out which part of the page the viewer is visiting (something like google books, to find out the page that's being viewed) :
$("#main-content").scroll(function () {
Nx.curPage = (Math.round($(this).scrollTop()/620)+1);
window.location.hash = "#"+Nx.curPage;
Nx.select(undefined);
});
also in another part I use $(window).resize( ... ) to fit my content in current window size, which is called for every single resize . as you can imagine this slows down the page alot, specially on older hardwares. Is there any way to realise when scrolling or resizing is stopped and then start doing the stuff, so number of processes is reduced ? something like $("#main-content").scrollStop ???
You can do two things.
1.) Set up a timeout so that resize/scroll only happens after some idle state:
var timeout;
$("#main-content").scroll(function () {
clearTimeout(timeout);
timeout = setTimeout(function(){
Nx.curPage = (Math.round($(this).scrollTop()/620)+1);
window.location.hash = "#"+Nx.curPage;
Nx.select(); // note: undefined is passed by default
}, 200);
});
2.) Limit the number of calls / sec:
var lastScroll = 0;
$("#main-content").scroll(function () {
var now = +new Date;
if (now - lastScroll > 100) { // only execute if (elapsed > 100ms)
Nx.curPage = (Math.round($(this).scrollTop()/620)+1);
window.location.hash = "#"+Nx.curPage;
Nx.select();
lastScroll = now;
}
});
Try the function below. It checks if the user has scrolled past a certain no. of pixels, but the function only fires at set intervals (5 times a second in the example below) rather than continuously during scrolling.
var scrollCheck;
$(window).on('scroll', function() {
clearInterval(scrollCheck);
scrollCheck = setInterval(function(){
clearInterval(scrollCheck);
scrollPosition = $(this).scrollTop();
scrollAmount = 150 // no. of pixels that have been scrolled from top
if(scrollPosition > scrollAmount){
alert('scrolled past point')
}else{
alert('not scrolled past point')
}
},200);
});