Reputation: 906
I have a jQuery function that adds a new menu area if the page is scrolled down past X pixels. All good. If the page is refreshed past the pixel value, the function is not triggered. I have tried adding (binding) an extra event to the function handler, but no joy. I have the desired effect working, but have resorted to extra code:
$(window).load(function()
{
var num = 130; //number of pixels before modifying styles
console.log($(window).scrollTop());
// i have tried load, ready. what can I do???
$(window).bind('load scroll', function()
{
if ($(window).scrollTop() > num)
{
$('.now_page').addClass('fixed');
$('.now_page_res').fadeOut(0);
$('.now_page_overlay').fadeIn(500).css("display","block").css("visibility","visible");
}
else
{
$('.now_page').removeClass('fixed');
$('.now_page_overlay').fadeOut(100).css("display","none").css("visibility","hidden");
$('.now_page_res').fadeIn(500);
//$('#cart_container').fadeIn(500);
}
});
// EXTRA CODE HERE.... FFS there must be a way to bind the function above to page load...
{
if ($(window).scrollTop() > num)
$('.now_page').addClass('fixed');
$('.now_page_res').fadeOut(100);
$('.now_page_overlay').fadeIn(500).css("display","block").css("visibility","visible");
}
});
Any sugestions on what I can do to get this to work without the extra code?
Upvotes: 0
Views: 208
Reputation: 3328
Trigger the scroll event on the window manually:
$(function () {
var num = 130,
$nowPage = $('.now_page'),
$nowPageOverlay = $('.now_page_overlay'),
$nowPageRes = $('.now_page_res');
$(window).bind('scroll', function () {
if ($(window).scrollTop() > num) {
$nowPage.addClass('fixed');
$nowPageRes.fadeOut(0);
$nowPageOverlay.fadeIn(500).css("display", "block").css("visibility", "visible");
} else {
$nowPage.removeClass('fixed');
$nowPageOverlay.fadeOut(100).css("display", "none").css("visibility", "hidden");
$nowPageRes.fadeIn(500);
}
});
$(window).trigger('scroll');
});
Upvotes: 1
Reputation: 318342
It's already inside window.onload, so just trigger the scroll event :
$(window).on('load', function () {
var num = 130;
$(window).on('scroll', function () {
if ($(window).scrollTop() > num) {
$('.now_page').addClass('fixed');
$('.now_page_res').fadeOut(0);
$('.now_page_overlay').fadeIn(500).css("display", "block").css("visibility", "visible");
} else {
$('.now_page').removeClass('fixed');
$('.now_page_overlay').fadeOut(100).css("display", "none").css("visibility", "hidden");
$('.now_page_res').fadeIn(500);
}
}).trigger('scroll'); // triggers the above function on window.onload
});
Upvotes: 1