jQuery Scroll to top fade in/out issue
Xavier’s Question:
This code has two parts:
The first one is supposed to fade in the .toTop button when the user scrolls down and keep it hide otherwise.
The second part is supposed to bring the user top when clicking on it.
Part two isn’t working when mixed with part one. I can’t find the conflict between the two.
<script>
$(document).ready(function(){
$(".toTop").hide();
$(function () {
$(window).scroll(function () {
if ($(this).scrollTop() > 300) {
$('.toTop').fadeIn();
} else {
$('.toTop').fadeOut();
}
});
});
});
var easing, e, pos;
$(function(){
$(".toTop").on("click", function(){
pos= $(window).scrollTop();
$("body").css({
"margin-top": -pos+"px",
"overflow-y": "scroll",
});
$(window).scrollTop(0);
$("body").css("transition", "all 1s ease");
$("body").css("margin-top", "0");
$("body").on("webkitTransitionEnd transitionend msTransitionEnd oTransitionEnd", function(){
$("body").css("transition", "none");
});
});
});
</script>
Use this…
$(document).ready(function(){
$(".toTop").hide();
$(function () {
$(window).scroll(function () {
if ($(this).scrollTop() > 200) {
$('.toTop').fadeIn();
} else {
$('.toTop').fadeOut();
}
});
});
});
var easing, e, pos;
$(function(){
$(".toTop").on("click", function(){
pos= $(window).scrollTop();
$("body").css({
"margin-top": -pos+"px",
"overflow-y": "scroll",
});
$(window).scrollTop(0);
$("body").css("transition", "all 1s ease");
$("body").css("margin-top", "0");
$("body").on("webkitTransitionEnd transitionend msTransitionEnd oTransitionEnd", function(){
$("body").css("transition", "none");
});
});
});
And dee this DEMO
First point is that, you have used to many .ready()
event handler. Remove all the redundancies:
$(document).ready(function(){
$(".toTop").hide();
$(window).scroll(function () {
if ($(this).scrollTop() > 300) {
$('.toTop').fadeIn();
} else {
$('.toTop').fadeOut();
}
});
var easing, e, pos;
$(".toTop").on("click", function(){
pos = $(window).scrollTop();
$("body").css({
"margin-top": -pos+"px",
"overflow-y": "scroll",
});
$(window).scrollTop(0);
$("body").css("transition", "all 1s ease");
$("body").css("margin-top", "0");
$("body").on("webkitTransitionEnd transitionend msTransitionEnd oTransitionEnd", function(){
$("body").css("transition", "none");
});
});
});