0

I am trying the jquery "Please Wait Loading Animation" as here

<script type="text/javascript">
        var body = $("body");

        $(document).on({
            ajaxStart: function () {
                console.log("ajax start");
                body.addClass("my-loading");
                console.log(body.hasClass("my-loading"));
            },
            ajaxStop: function () {
                console.log("ajax stop");
            }//$body.removeClass("my-loading"); }}
        });
    </script>

But I get false when log the class with console.log(body.hasClass("my-loading"));

Why is the class not getting added?

EDIT

The above code is in header section.

Community
  • 1
  • 1
rahulserver
  • 10,411
  • 24
  • 90
  • 164

2 Answers2

1

Put all your code in $(document).ready(function() { });

Or:

$(function(){
     //jQuery 
});
brroshan
  • 1,640
  • 17
  • 19
  • Hmm, not sure that's relevant in this case, though maybe it is if the script is in the head section. But document.ready definitely isn't needed if the script is right before the closing body tag. – Matt Browne Aug 09 '15 at 21:31
  • @MattBrowne this actually helps. the var body=$('body') was getting called before the body has loaded. Hence on moving this particular thing in $(function()){} helped it load the body properly – rahulserver Aug 10 '15 at 05:18
  • Cool, glad you solved it. Btw, pages load faster if scripts are at the bottom (right before the closing body tag), rather than in the head section, although there are still reasons you might want a script to load earlier in some cases. – Matt Browne Aug 10 '15 at 11:16
1

It would be better if we could see your ajax call as well since $.ajaxStart triggers when the ajax call is being done, not during the event that triggered the start of the ajax. If we can see the ajax call itself we can rule out the possibility that the ajax call is malformed or something.

Also, have you tried this implementation instead?

var body = $("body");
$(document).ajaxStart(function () {
    body.addClass("myClass");
    console.log(body.hasClass("myClass"));
});
$(document).ajaxStop(function () {
  //...
});

As a side note, unless you want to put the body variable in the global namespace you should reference it in your ajaxStart() logic.

Ju66ernaut
  • 2,592
  • 3
  • 23
  • 36