Is there a particular reason why the script I am troubleshooting will not apply their assigned classes, or styles? I have tried different methods, (in an attempt to achieve the same result), but nothing has worked so far...
FIRST ATTEMPT:
Here was my initial attempt with .toggleClass()
, (which worked in Firefox and Chrome, but did not fire at all Safari):
$(document).ready(function() {
var $window = $(window);
var div2 = $('#pgnav');
var div1 = $('#container2');
$window.on('scroll', function() {
var scrollTop = document.documentElement.scrollTop;
var viewport_height = $window.height();
var scrollTop_bottom = scrollTop + viewport_height;
var window_top_to_div2 = ($window.height() - div2.height()) / 2;
var div1_top = div1.offset().top;
var div1_height = div1.height();
var div1_bottom = div1_top + div1_height;
div2.toggleClass('show', scrollTop >= (div1_top - window_top_to_div2) && (scrollTop + window.innerHeight) <= (div1_bottom + window_top_to_div2));
});
});
Additionally, here is an excerpt of the CSS:
#pgnav {
visibility: hidden;
opacity: 0;
}
#pgnav.show {
visibility: visible;
opacity: 1;
}
SECOND ATTEMPT: Then I swiched out .toggleClass()
for .addClass()
/.removeClass()
, (and still no luck):
$(document).ready(function() {
var $window = $(window);
var div2 = $('#pgnav');
var div1 = $('#container2');
$window.on('scroll', function() {
var scrollTop = document.documentElement.scrollTop;
var viewport_height = $window.height();
var scrollTop_bottom = scrollTop + viewport_height;
var window_top_to_div2 = ($window.height() - div2.height()) / 2;
var div1_top = div1.offset().top;
var div1_height = div1.height();
var div1_bottom = div1_top + div1_height;
if (scrollTop >= (div1_top - window_top_to_div2) && (scrollTop + window.innerHeight) <= (div1_bottom + window_top_to_div2)) {
div2.addClass('show')
} else {
div2.removeClass('show');
}
});
});
THIRD ATTEMPT: Finally, I attempted to use .css()
instead of .addClass()
/.removeClass()
, and it still delivered no response in Safari:
if (scrollTop >= (div1_top - window_top_to_div2) && (scrollTop + window.innerHeight) <= (div1_bottom + window_top_to_div2)) {
div2.css('display', 'inline');
} else {
div2.css('display', 'none');
}
FOURTH ATTEMPT: Here's something else I've tried, based on this post here: https://stackoverflow.com/a/11325039/9214076, (but still no luck!):
if (scrollTop >= (div1_top - window_top_to_div2) && (scrollTop + window.innerHeight) <= (div1_bottom + window_top_to_div2)) {
div2.css('display', 'inline').parent().addClass("dummyClass").removeClass("dummyClass");
} else {
div2.css('display', 'none').parent().addClass("dummyClass").removeClass("dummyClass");
}
Why won't Safari run any of these script variations? Though the task at hand seems straightforward enough, nothing seems to resolve the issue...
Also, to see a full snippet of this in action, I advise you to visit my previous post here: Can toggleClass Work in Safari? (JQuery)