0

I have an MVC application in which the top menu is build dynamically like so:

 $.each(data, function (index, dataMenu) {
                if (i == 0) {
                    stringBuilder.push('<li class="home"><a href="#">' + dataMenu.MenuName + '</a></li>');
                    i++;
                }
                else {


                    stringBuilder.push('<li class="dropdown"><a href="#" class="dropdown-toggle" data-toggle="dropdown">' + dataMenu.MenuName + '</a>');
                    stringBuilder.push('<ul class="dropdown-menu">');
                    $.each(dataMenu.GetallMenus, function (index, submnu) {
                        stringBuilder.push('<li class=""><a data-ajax="true" data-ajax-mode="replace" data-ajax-update="#content-area" href="' + submnu.MenuItemUrl + '">' + submnu.MenuName + '</a></li>');
                    });
                    stringBuilder.push('</ul>');
                    stringBuilder.push('</li>');
                }
            });
            stringBuilder.push('</ul>');
            $("#menu").append(stringBuilder.join(''));

There's a loader gif in a div tag on _Layout.cshtml and on document.ready it's hidden initially.

What I am trying to do is to show that div on every menu click.

How do I go about doing it?

Regards.

Codehelp
  • 4,157
  • 9
  • 59
  • 96
  • 2
    Do you mean this question? http://stackoverflow.com/questions/16893043/jquery-click-event-not-working-after-adding-class-using-jquery – Coder Aug 19 '13 at 07:30

2 Answers2

0

Can't you just do this outside the loop?

$('#menu li').click(function()
{
    showSpinner();
}

Maybe I'm reading the question wrong.

Oskar Hane
  • 1,824
  • 13
  • 8
0

You could do this, to avoid setting the listener for each element.

$(document).on("click", "your target query", function(){
    // Your click logic
});

So that would result to:

$(document).on("click", "#menu li.someClass", function(){
    // Your click logic
});

This will work wether you add or remove menu items dynamically, and only needs to be called once.

André Snede
  • 9,899
  • 7
  • 43
  • 67