Adding jQuery Click function inside for loop

I'm going crazy. So I have a click function that creates a new div with unique classes and everything else.

Inside all of them there is a button (another click function .varibFixed) that hides and shows divs inside divs that are created with the said click function.

My goal is for this button to work for all new divs that are created. My code is below, but it just doesn't work for newly created divs - only the first div.

var interest = function () {
    $('.varibFixed').click(function () {
        for (var k = 1; k < i; k++) {
            if ($(this).hasClass('fixed' + k)) {
                $('.Ffixed' + k).removeClass('interestOpt');
                $('.Ffixed' + k).addClass('showInt');
                $('.Fvariable' + k).removeClass('showInt');
                $('.Fvariable' + k).addClass('interestOpt');

            } else if ($(this).hasClass('variable' + k)) {
                $('.Fvariable' + k).removeClass('interestOpt');
                $('.Fvariable' + k).addClass('showInt');
                $('.Ffixed' + k).removeClass('showInt');
                $('.Ffixed' + k).addClass('interestOpt');
            }

        }
    });
};

      

+3


source to share


1 answer


It looks like you need a jQuery handler .on

.

The following example will attach an event handler for all elements that match the current selector, now and in the future .



The key to understanding why your code was not working is that it click

will only work for a selected set of elements on the page , not future ones.

var interest = function () {
    $(document).on('click', '.varibFixed', function () {
        for (var k = 1; k < i; k++) {
            if ($(this).hasClass('fixed' + k)) {
                $('.Ffixed' + k).removeClass('interestOpt');
                $('.Ffixed' + k).addClass('showInt');
                $('.Fvariable' + k).removeClass('showInt');
                $('.Fvariable' + k).addClass('interestOpt');

            } else if ($(this).hasClass('variable' + k)) {
                $('.Fvariable' + k).removeClass('interestOpt');
                $('.Fvariable' + k).addClass('showInt');
                $('.Ffixed' + k).removeClass('showInt');
                $('.Ffixed' + k).addClass('interestOpt');
            }

        }
    });
};

      

+1


source







All Articles