Javascript/jQuery scrollTop issue - javascript

I've re-created a simple version of what I'm trying to do here (jsFiddle)
The header should stay where it is, and as you scroll down, when you click the header div it should scroll back up to the top, which it does. But if you focus on the input, or click the "logo", the scroll should stay where it is.
With the first method I've tried is by using jQuery's .css and setting the input/logo's z-index as higher than the header, then getting the current scroll and keeping it at that position.
This sort of works, but once you click the input or logo, the header scroll no longer works.
I've also tried changing the logo/input jQuery to .animate with a slow speed, and it stays static for a couple seconds and then scrolls to the top even though I've not set it to do so. Here is the second example - jsFiddle
Doing it with the second example however doesn't stop the other function from working.
Is there any reason for this behaviour that I'm missing?

You can prevent the click event from propagating to the header.
$("#logo, #input").click(function(e) {
e.stopPropagation();
});

Check out this interesting article about event order, all you have to do is stop propagation. Here your modified Fiddle
$("#logo, #input").click(function(e) {
e.stopPropagation();
var y = window.scrollY;
$('html').animate({
scrollTop: y
}, 'slow');
$('body').animate({
scrollTop: y
}, 'slow');
});

All you need to do is stop the propegation of the event. To do this you return false from your click function.
$("#logo, #input").click(function() {
return false; // Add this line
});
Here is your fiddle updated: http://jsfiddle.net/BRnvT/

Related

how to attach scroll event to window after scroll animation

I'm trying to display a div after scroll animation has finished and hide it when I scroll up/down the page. This is my attempt:
$('#cta').on('click', function(e) {
e.preventDefault();
$('#layer, #servicesContent').addClass('active');
var position = parseInt($('#services').offset().top);
$('html, body').animate({
scrollTop: position - 100
}, 'slow', function() {
$(window).bind('scroll', function() {
$('#layer, #servicesContent').removeClass('active');
});
});
});
it doesn't work. the active class is removed after animation has finished and not with scroll movement.
Any idea?
Thanks in advance
Not exactly sure why, but apparently it takes the window somewhere around 20 milliseconds to exit the scroll state, at least on Chrome, on Windows. Or it might be a jQuery trick to fire the animation function 20ms sooner, so it feels more natural. (Human eye and mind make connections that take tiny amounts of time and maybe they took it into account).
Anyway, in order to make sure you bind after the scroll has ended, give it a full 100ms to finish and bind afterwards:
$('#cta').on('click', function(e) {
e.preventDefault();
$('#layer, #servicesContent').addClass('active');
var position = 120;
$('html, body').animate({
scrollTop: position - 100
}, 'slow', function() {
setTimeout(function(){
$(window).bind('scroll', function() {
$('#layer, #servicesContent').removeClass('active');
});
},100)
});
});
working fiddle.
Please note I had hard-coded a value to position, as #services is not defined in my example.
Also please note that hiding events on scroll is a really bad idea in terms of usability. Users might want to scroll so they view the div better or read it in full, but they will end up hiding it, which would be annoying. I would at least check the scroll event for a minimum velocity or distance in order to hide an element from the screen.

Jquery scroll until element reaches top

I have arrows in the center of my web pages at the end of sections and I was these to allow users to scroll to the next section on click. I have the following code where the first click works but subsequent clicks do not scroll even though the function is being called each time.
$('.scroll').on('click', function(event) {
alert('scroll');
$('html, body').animate({
scrollTop: $(".scroll").offset().top
}, 1000);
});
Can anyone assist? https://jsfiddle.net/avL459sm/2/
You should use current .scroll element you clicked on.
Look at this fiddle: https://jsfiddle.net/avL459sm/3/

JQuery .scrollTop() and .offset().top issue: how it work? How to solve?

I want to achieve some kind of smooth scrolling, so I made this script:
$('a').click(function(){
var sclink = $(this).attr('href');
$('.menu').animate({
scrollTop: $(sclink).offset().top
}, 500);
return false;
});
The problem? When I click on the 'a' the offset.top() value changes in another weird value and toggle between them? Why does this happen and how do I resolve it?
http://jsfiddle.net/StartStep/9SDLw/2947/
I think the problem is with the scroll.top() that gets the value in another way...
jsfiddle.net/9SDLw/2950/
$('a').click(function(){
var sclink = $(this).attr('href');
$('.menu').animate({
scrollTop: $(sclink).position().top
}, 500);
logit('Anchor: '+sclink+'; Offset top value: <b>'+$(sclink).offset().top+'</b>')
return false;
});
Use position instead of offset.
The reason is offset is relative to the viewport, as such it looks like you've scrolled too far, but this is because the top of your viewport area is being obscured by your layout, so offset is actually not what you want, instead, position is.
You should also add a reference to stop before calling animate to ensure if a user clicks in quick succession the behaviour is as expected (the animation queue is essentially flushed)
With that in mind your HTML also needs some work- the clickable link hasnt got closing tags for example.
Change your scrolling code to:
$('.menu').stop(true,true).animate({
scrollTop: $(sclink).position().top
}, 500);
Demo Fiddle

Follow cursor on scrolling page

On my page I have new comment box's that stack on top each other every couple of seconds. is their a way to follow the comment box I click on. currently if i click it that box gets pushed off the screen when the other box's load on top and have to scroll down manually to it. I would like to auto follow that box I click on... Focus?
You can use an anchor:
<div id="aDiv"></div>
then
location.href = "#";
location.href = "#aDiv";
Or you can use jquery scrollTop: scrollTop: $(this).offset().top
Or you can use javascript scrollTo: window.scrollTo(elementPos,0)
So, to set the scroll, https://developer.mozilla.org/en-US/docs/Web/API/Element.scrollTop
I would implement this 2 ways
An observer pattern with the boxes, that knows when new boxes are added, which checks a flag. The flag itself is set true when there is focus on any comment box, and false when there is not.
Scrolltop can be jarring in a UI, but perhaps you can figure out a way to animate it, I won't spoon feed you further.
Check out Addy Osmanis book if you need help with design patterns!
http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/
You can use the scrolltop function in jQuery.
//Everytime, you add a comment, scroll the page to the element
$('html, body').animate({
scrollTop: $("#clickedComment").offset().top
}, 500);
Here's a complete fiddle but you will see that there is a logic problem. It's not possible to scroll up when you have many comment above.

$(window).scroll() firing on page load

Is there a way to prevent $(window).scroll() from firing on page load?
Testing the following code in Firefox 4, it fires even when I unplug the mouse.
jQuery(document).ready(function($){
$(window).scroll(function(){
console.log("Scroll Fired");
});
});
The scroll event is unrelated to the mouse, it is called whenever a new document scrolling position is set. And arguably that position is set when the document loads (you might load it with an anchor after all), also if the user presses a cursor key on his keyboard. I don't know why you need to ignore the initial scroll event but I guess that you only want to do it if pageYOffset is zero. That's easy:
var oldPageYOffset = 0;
$(window).scroll(function(){
if (window.pageYOffset != oldPageYOffset)
{
oldPageYOffset = window.pageYOffset;
console.log("Window scrolling changed");
}
});
Note: MSIE doesn't have window.pageYOffset property so the above will need to be adjusted. Maybe jQuery offers a cross-browser alternative.
This was the solution I went for. Any improvements gratefully received.
var scroll = 0;
$(window).scroll(function(){
if (scroll>0){
console.log("Scroll Fired");
}
scroll++;
});
The scroll event does not fire on every load, only when refreshing a page that was scrolled, or when navigating to an anchor directly.
Many of the answers suggest ignore the first time it's called, which would ignore a valid scroll if the page doesn't get scrolled initially.
//Scroll the page and then reload just the iframe (right click, reload frame)
//Timeout of 1 was not reliable, 10 seemed to be where I tested it, but again, this is not very elegant.
//This will not fire initially
setTimeout(function(){
$(window).scroll(function(){
console.log('delayed scroll handler');
});
}, 10);
//This will fire initially when reloading the page and re-establishing the scroll position
$(window).scroll(function(){
console.log('regular scroll handler');
});
div {
height: 2000px;
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
</div>
This seems to have worked for me.
$(window).bind("load", function() {
$(window).on("scroll", function () {
console.log('scroll');
});
});
sure, don't load it until after the load. make it a call back for sleep for 500 millis.

Categories