It seems that my jQuery code is not running in Chrome as expected.
The purpose of my jQuery code is to determine if an element is within the viewport or not.
function isElementInViewport(elem) {
var $elem = $(elem);
// Get the scroll position of the page.
var scrollElem = ((navigator.userAgent.toLowerCase().indexOf('webkit') != -1) ? 'body' : 'html');
var viewportTop = $(scrollElem).scrollTop();
var viewportBottom = viewportTop + $(window).height();
// Get the position of the element on the page.
var elemTop = Math.round($elem.offset().top);
var elemBottom = elemTop + $elem.height();
return ((elemTop < viewportBottom) && (elemBottom > viewportTop));
}
// Check if it's time to start the animation.
function checkPhp() {
var $elem = $('.progress #fullPHP');
// If the animation has already been started
if ($elem.hasClass('start')) return;
if (isElementInViewport($elem)) {
// Start the animation
$elem.addClass('start');
}
}
$(window).scroll(function () {
checkPhp();
});
/* Css Annimation */
@keyframes phpProgress{
from {width: 0%;}
to {width: 25%;}
}
@-webkit-keyframes phpProgress{
from {width: 0%;}
to {width: 25%;}
}
@-moz-keyframes phpProgress{
from {width: 0%;}
to {width: 25%;}
}
@-o-keyframes phpProgress{
from {width: 0%;}
to {width: 25%;}
}
#fullPHP.start {
width: 0px;
-webkit-animation: phpProgress 5s ease-out forwards;
-moz-animation: phpProgress 5s ease-out forwards;
-ms-animation: phpProgress 5s ease-out forwards;
-o-animation: phpProgress 5s ease-out forwards;
animation: phpProgress 5s ease-out forwards;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<h5>PHP</h5>
<br>
<div class="progress purple lighten-3">
<div id="fullPHP" class="determinate purple darken-3"></div>
</div>
</body>
Intriguingly, the JavaScript code works well in every browser except for Chrome. Why does Chrome behave differently?
Could there be something specific to Chrome that I missed out?
Is it possible that the same code results in different outcomes on different browsers? Would utilizing vanilla JS resolve this issue?
https://i.sstatic.net/DkbRy.png
I am puzzled by Chrome returning false while other tested browsers return true. Any insights on this discrepancy?
EDIT:
Following the suggestion to call the function within the scroll event, the issue was resolved. However, the console displayed errors until the element entered the viewport. I initially believed my if statement would invoke the function.
$(window).scroll(function () {
checkPhp();
});
Here is the jsFiddle link: https://jsfiddle.net/Achmann/p854nuoc/4/