1

I have a MVC 4 application with Basic template. In the _layout.cshtml I have this code:

<script type="text/javascript">
        $(window).load(function () {
            $("body").on({
                // When ajaxStart is fired, add 'loading' to body class
                ajaxStart: function () {
                    $(this).addClass("loading");
                },
                // When ajaxStop is fired, remove 'loading' from body class
                ajaxStop: function () {
                    $(this).removeClass("loading");
                }
            });

            $("a").click(function () {
                $(this).addClass("loading");
            });
        });

    </script>

And the HTML in the same:

<body>
    @RenderBody()

    @Scripts.Render("~/bundles/jquery")
    @RenderSection("scripts", required: false)
    <div class="modal"></div>
</body>

I created a HomeController which has just the code given by MVC. In the Index view all I have is this:

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
<a href="#">some <span class="red">text</span></a>

I am trying to understand on how to implement a loader whenever a link or an ajax request is made across the application.

Got a lot of help from here and here.

The above code is not showing the loader when the link is clicked, there aren't any ajax calls as of now. This is a very simple thing for a lot of jQuery gurus out there but I am having a hard time understanding the events hookup using jQuery so I am trying to learn with small baby steps.

Can someone guide me on how to show the loader and hide it?

Appreciate your help. Regards.

Community
  • 1
  • 1
Codehelp
  • 4,157
  • 9
  • 59
  • 96

2 Answers2

0

Try this, if a is not created dyanmically, if a is created on runtime then need to bind while creation time.

<script type="text/javascript">
    $(function () {
        $("body").on({
            // When ajaxStart is fired, add 'loading' to body class
            ajaxStart: function () {
                $(this).addClass("loading");
            },
            // When ajaxStop is fired, remove 'loading' from body class
            ajaxStop: function () {
                $(this).removeClass("loading");
            }
        });

        $("a").click(function () {
            $(this).addClass("loading");
        });
    });

</script>

Demo

Amit
  • 15,217
  • 8
  • 46
  • 68
0

If a is created dynamicly, you cannot use click() function. Try this one

 $("a").on('click',function () {
            $(this).addClass("loading");
        });
Kuzgun
  • 4,649
  • 4
  • 34
  • 48