Wait for JQuery execution until whole page is loaded breaks execution
I have a JQuery script to load a newsletter subscription popup window after the users scrolls down a certain amount of pixels using the jQuery .scroll/.scrollTop function.
At the moment it's all encapsulated within
jQuery(document).ready(function($)
The problem is the usual caching and images issue and the subscription box pops up all over the place. I was reading about delaying jQuery using the .load function until the page is fully loaded. However when I replace
jQuery(document).ready
with
jQuery(window).load(function($){
//your code here
});
the functionality breaks completely.
I want to note that I am using WordPress and have the script enqueued like this:
function enfold_child_custom_scripts(){
// Register and Enqueue a Script
// get_stylesheet_directory_uri will look up child theme location
wp_register_script( 'custom-js', get_stylesheet_directory_uri() . '/custom.js', array('jquery'));
wp_enqueue_script( 'custom-js' );
}
add_action('wp_enqueue_scripts', 'enfold_child_custom_scripts');
Here is my JS/jQuery code as it is right now.
jQuery(document).ready(function($) {
jQuery("#nl-pop").hide(); //hide nl block initially
var disableFade = "false";
var startShowTop = jQuery("#newsletter-cta").offset().top - 3500;
var startHide = jQuery("#newsletter-cta").offset().top - jQuery(window).height(); //Hide when the viewport is reached
jQuery('#no-thanks').click(function(event) {
event.preventDefault();
jQuery('#nl-pop').fadeOut('slow');
disableFade = "true";
});
jQuery(window).scroll(function() {
if(jQuery(window).scrollTop() < (startShowTop) ) //when scrollposition is smaller than the first point
{
jQuery("#nl-pop").fadeOut(200); // Hide when in the upper part of the page
}
else //when reached the lower part of the page
{
if(jQuery(window).scrollTop() > startShowTop && $(window).scrollTop() < startHide && disableFade==="false") { //When reached the show position but not as far down as the hide position
jQuery("#nl-pop").fadeIn(200); //show
}
else if(jQuery(window).scrollTop() > (startHide) ) { //scrolled down to the bottom newsletter box
jQuery("#nl-pop").fadeOut(200); //hide
}
}
});
});
Solutions
Move the calculation of
startShowTop
and
startHide
to be inside of
.scroll()
. That way their value won't suffer from unloaded elements. They will instead be dependent on the current state of the page (which will most likely be after entire page has loaded).