Having trouble getting Chrome to execute my jQuery code

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/

Answer №1

When trying to run your code in jsFiddle, it's not working because you've included the full HTML layout within the HTML window. This means that the HTML tags like <html>, <head>, etc., are present, preventing jsFiddle from adding its own necessary settings such as the run javascript onload.

The issue with your current code lies in the fact that you're not checking the correct element for the scroll. Instead of using the body tag, consider using window or html instead.

var viewportTop = $(window).scrollTop();
var viewportBottom = viewportTop + $(window).height();

For a demo:

function isElementInViewport(elem) {
  var $elem = $(elem);

  var viewportTop = $('html').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));
}


function checkPhp() {
  var $elem = $('.progress #fullPHP');
  if ($elem.hasClass('start')) return;
  if (isElementInViewport($elem)) {
    $elem.addClass('start');
  }
}

$(window).scroll(function() {
  checkPhp();
});
/* Progress Bars */
@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>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/css/materialize.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/js/materialize.min.js"></script>
<title>Document</title>

<!-- Your content -->

Answer №2

Revised

Adjusted for optimal performance:

function isElementInViewport(elem) {
    var $elem = $(elem);

    // Determine the scroll position of the page
    var viewportTop = $(window).scrollTop();
    var viewportBottom = viewportTop + $(window).height();

    // Find 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 initiate the animation.
function checkPhp() {
    var $elem = $('.progress #fullPHP');

    // Ensure the animation has not already started
    if ($elem.hasClass('start')) return;

    if (isElementInViewport($elem)) {
        // Begin the animation
        $elem.addClass('start');
    
    }
}

$(window).scroll(function () {
   checkPhp();
 

});
/* Progress Bars */
@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>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/css/materialize.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/js/materialize.min.js"></script>
    <title>Document</title>
</head>
<body>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis ipsum. Praesent mauris. Fusce nec tellus sed augue semper porta. Mauris massa. Vestibulum lacinia arcu eget nulla. </p>
... (continued text) ... 

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

conducting a validation using ajax when submitting

Currently, I am exploring the implementation of AJAX validation within a submit() handler for a web form. The AJAX functionality is executed using $.ajax() from jQuery. While setting async: false yields successful results, it triggers a deprecation notice, ...

Ways to verify if an image is captured from the device's camera using HTML5

I'm facing a unique challenge that may be considered an edge case. The situation is that I am currently in the process of developing a website that functions as a mobile application (similar to a mobile-first website). In order to achieve this, I have ...

Exploration of the "display: none;" property and loading of content

I am struggling to find concrete information on how "display: none;" affects content loading. I have always believed that certain browsers do not load external resources within content that is styled with "display: none". Is this still inconsistent across ...

Creating a form for adding and editing using React Hook Form

I'm currently working on creating a form that can handle both the creation and editing of a product by passing values through an object. The form functions perfectly for creating a product, but I'm facing challenges in making it work for editing ...

Differences in weekend start and end days vary across cultures

Looking for a solution to determine the weekend days per culture code in Typescript/Javascript? While most countries have weekends on Sat-Sun, there are exceptions like Mexico (only Sunday) and some middle-eastern countries (Fri-Sat). It would be helpful ...

Is the ng-model feature not functioning as anticipated?

Within my AngularJS application, I have a textbox connected with the directive ng-model=sampleValue. My goal is to change the value of the textbox to "Harish" whenever I click on a button that triggers the show function. However, I am encountering issues ...

Tips for concealing XHR Requests within a react-based single page application

Is there a way to hide the endpoint visible in Chrome's devtools under the network tab when data is fetched in React? Can server-side rendering solve this issue? ...

To link the information within the angularJS controller

I've recently generated a div element dynamically within the controller function of my AngularJS application. However, I'm facing an issue where the data is not binding as expected inside this div element. Here is a snippet of my code: function ...

Options for managing URLs with jQuery

I've been working with a jQuery user interface component called aciTree, which is a tree list that uses Ajax as the data source. When I provide a URL that returns JSON, everything functions properly. However, I need to generate the JSON dynamically an ...

Submitting a form and using Ajax to upload an image

Is there a way to submit an image file to php using ajax without assigning the file to a variable with onchange event? I've tried triggering the request on submit click, but keep getting the error message: "cannot read property 0 of undefined." <ht ...

React Native List component with interactive items

I am currently developing a custom line style for a react-native FlatList. My goal is to allow the user to navigate to item details by clicking on the line text, or to navigate to another page (drill down to the next level) by clicking on the right caret ...

What is the best way to handle escape characters in a string in JavaScript?

Within a file named file-a.php, I have created a custom shortcode that generates the following simplified HTML structure: <div><a href="#"><span>Link text</span></a></div> In another file, file-b.php, I retrieve the [s ...

Concealing excess background color in HTML/CSS

I'm currently experimenting with adding a background color shape, such as a large rotating div, to the background of my website. However, I've encountered an issue where placing this background in the desired location is causing a large margin to ...

When trying to display an image using CSS, the image does not appear on the screen

I've been working on streamlining my HTML code and moving as much as possible to my CSS file. However, I'm facing an issue with getting an image to display when writing the CSS code for it. Here's the HTML: <html> <head> <l ...

Warning: Unhandled Promise Rejection occurs when a date field is left empty

Currently in the process of building a website using MEAN stack, and everything is nearly complete. However, I've encountered an issue with the "user editing his/her profile" functionality. Whenever the user makes edits along with changing their birth ...

Is there a way to combine two objects within an array and calculate the sum of their elements?

Can anyone suggest a method to merge objects and calculate the total number of their elements simultaneously? I'm struggling to find a way to combine them while also adding up the chats count. Here is an example array: [ [ { id: ' ...

When using JSON stringify, double quotes are automatically added around any float type data

When passing a float data from my controller to a JavaScript function using JSON, I encountered an issue with quotes appearing around the figure in the output. Here is the JS function: function fetchbal(){ $.ajax({ url: "/count/ew", dataType: "jso ...

Create a webpage that utilizes PHP, MySQL, and HTML to load additional content in a way similar to Facebook or the

Seeking guidance on how to incorporate pagination functionality akin to Twitter and Facebook, where a list of items loads initially and then a "load more" button appears below. When clicked, this button appends the list with additional items. Can anyone ...

Set attributes to the main ul elements

My knowledge of jquery is still developing, and I have encountered what seems to be a fairly straightforward issue. I am in the process of setting up a flyout menu for navigation on a new website. However, due to restrictions imposed by my CMS, I am unabl ...

Use HTML to showcase an image that dynamically changes based on the outcome of a query function

Hello there, I hope my inquiry is clear enough. I apologize for reaching out as I am unsure where to begin and what exactly I should be focusing on. Currently, I have an image displayed in an HTML page like this: <div id="tag_sunrise_sunset"><p ...