ecampose76
ecampose76

Reputation: 11

jQuery / JavaScript code not working on iPhones

I have been trying this code for a webpage preloader and it works well on all devices except iPhone. The code is for a loading bar and at 100% it should fade out, but on iPhones it just gets stuck and never fades out.

Can anyone help me figure out why?

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

    
    <script type="text/javascript">
            var progress = 0;
            document.onreadystatechange = function() {
                if(document.readyState == "interactive") {
                    var allElement = $("*");
                    var length = allElement.length;
                    for( var i = 0; i < length; i++ ) {
                        set_element(allElement[i], length);
                    }
                }
            }
        function set_element(element, totalElement) {
            var percentage = 100 / totalElement;
            if($(element).length == 1) {
                $("#fill").animate({ width:progress+percentage+"%" }, 200, function() {
                    if(document.getElementById("fill").style.width=="100%") {
                        $(".main").fadeOut(1200);
                    }
                });
                progress = progress + percentage;
            }
        }
    </script>

Upvotes: 1

Views: 65

Answers (1)

Barmar
Barmar

Reputation: 780723

The probably is most likely due to floating point inaccuracy, so when you add up all the percentages, it ends up being something like 99.999999% or 100.0000001%, not exactly 100%.

You should pass both i and length to set_element, then it can calculate the percentage directly, rather than incrementing the global variable.

document.onreadystatechange = function() {
  if (document.readyState == "interactive") {
    var allElement = $("*");
    var length = allElement.length;
    for (var i = 0; i < length; i++) {
      set_element(allElement[i], length, i);
    }
  }
}

function set_element(element, totalElement, curIndex) {
  var percentage = 100  * (curIndex / totalElement);
  if ($(element).length == 1) {
    $("#fill").animate({
      width: percentage + "%"
    }, 200, function() {
      if (document.getElementById("fill").style.width == "100%") {
        $(".main").fadeOut(1200);
      }
    });
    progress = progress + percentage;
  }
}

Upvotes: 1

Related Questions