I have an element that fills the screen, under that is another element but this one is hidden so you can’t scroll to it manually.
My CSS stylesheet looks like this for that:
body { height: 100%; width: 100%; margin: 0; padding: 0; } #page1, #content { height: 100%; width: 100%; position: absolute; } #content { top: 100%; display:none; }
#page1
stands for the element that fills the screen and #content
stands for the element which is underneath that.
When I click on a button on the first element (which fills the screen), it shows the element under that and smoothly scrolls down to that.
I was using this piece of code in the first place:
$(document).ready(function() { $('#exploreBtn').on('click', function() { $('#content').fadeIn(500); console.log($("#content").offset().top) $('html, body').animate({ scrollTop: $("#content").offset().top }, 1000, function(){ $("#page1").css('display','none'); $('#content').css('top',0); $(document).scrollTop(0); }); }); });
Which works in IE and Mozilla, but I’ve tried to improve it…
Now I’m using this code:
$(function() { var headerLoaded = true, contentLoaded = false, header = "#fitScreen", exploreBtn = "#exploreBtn", scrollBackBtn = "#scrollBackBtn", content = "#content"; $(exploreBtn).on('click', function() { if (!contentLoaded && headerLoaded) { showScrollHide(content, header, function() {zit var sum = ($('nav').height()) + parseInt($('nav').css('margin-bottom')); $('#panelContent').css('margin-top', sum); $('#content').css('top', 0); $('html, body').css('overflow-y', 'auto'); $(window).scrollTop(0); headerLoaded = false; contentLoaded = true; }); } }); var showScrollHide = function(element, hide, func) { $(element).fadeIn(500, function() { $('body').animate({ scrollTop: $(element).offset().top }, 1000, function() { $(hide).fadeOut(100, func); }); }); }; });
And for some reason, it doesn’t work on IE and Mozilla.
It just gives me a slight delay, and then it fades in the screen I’m scrolling to.
Can anyone help me with this?
Advertisement
Answer
In your new code, you have this part :
$(element).fadeIn(500, function() { $('body').animate({ scrollTop: $(element).offset().top }, 1000, function() { $(hide).fadeOut(100, func); }); });
The difference between your working code and your not working code is which element you animate the scroll.
In you working code, you are animating 'body, html'
. Depending on browser, the scrollbar is not on the same element. Hence, that’s why you should target both html and body element :
$(element).fadeIn(500, function() { $('html, body').animate({ //HERE! scrollTop: $(element).offset().top }, 1000, function() { $(hide).fadeOut(100, func); }); });