问题
I have more than one scroll function like this:
FIRST
$(document).scroll(function(){
if(!$(".hotel-search-box").length){
return false;
}
var y = $(this).scrollTop();
if (y > $(".hotel-search-box").offset().top) {
$('.sticky-checkin').show();
} else {
$('.sticky-checkin').hide();
}
});
SECOND
$(document).scroll(function() {
if (!$("#aniStickyNav").length) {
return false; //Check if the element exist
}
var y = $(this).scrollTop();
if (y > $(".after-scroll-sticky").offset().top+$(".hotel-search-box").height()) {
$('#aniStickyNav').show();
} else {
$('#aniStickyNav').hide();
}
});
THIRD
$(window).on('scroll', function () {
backToTop();
});
I tried this way
$(window).scroll(function(){
function siziArayalim(){
var y = $(this).scrollTop();
if (y > 800) {
$('.sizi-arayalim').fadeIn();
} else {
$('.sizi-arayalim').fadeOut();
}
}
function aniStickyNav(){
if (!$("#aniStickyNav").length) {
return false; //Check if the element exist
}
var y = $(this).scrollTop();
if (y > $(".after-scroll-sticky").offset().top+$(".hotel-search-box").height()) {
$('#aniStickyNav').show();
} else {
$('#aniStickyNav').hide();
}
}
function stickyCheckin(){
if(!$(".hotel-search-box").length){
return false;
}
var y = $(this).scrollTop();
if (y > $(".hotel-search-box").offset().top) {
$('.sticky-checkin').show();
} else {
$('.sticky-checkin').hide();
}
}
siziArayalim();
aniStickyNav();
stickyCheckin();
});
but nothing works
and because of more than one scroll function some js functions is not working as expected that is why I wonder that how to combine all window.scroll
function in a just one function healthy ?
回答1:
There are some issues with your code, first one is that you declare your functions inside the scroll function. This is not OK for performance. The second one is $(this) you are using inside the functions. I don't know what "this" is. In that context you are using, this will be the window object but i don't think that's what you need. Need more info here.
function siziArayalim(){
var y = $(this).scrollTop();
if (y > 800) {
$('.sizi-arayalim').fadeIn();
} else {
$('.sizi-arayalim').fadeOut();
}
}
function aniStickyNav(){
if (!$("#aniStickyNav").length) {
return false; //Check if the element exist
}
var y = $(this).scrollTop();
if (y > $(".after-scroll-sticky").offset().top+$(".hotel-search-box").height()) {
$('#aniStickyNav').show();
} else {
$('#aniStickyNav').hide();
}
return true;
}
function stickyCheckin(){
if(!$(".hotel-search-box").length){
return false;
}
var y = $(this).scrollTop();
if (y > $(".hotel-search-box").offset().top) {
$('.sticky-checkin').show();
} else {
$('.sticky-checkin').hide();
}
return true;
}
$(window).scroll(function(){
siziArayalim();
// check if the functions return false, if not, continue
if(!aniStickyNav()){
return false;
}
if(!stickyCheckin()){
return false;
}
});
来源:https://stackoverflow.com/questions/39567151/is-there-any-way-to-combinecollect-all-scroll-functions