Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a jQuery Click function inside of a for loop [duplicate]

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

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

My goal is to have that button work for all the new divs that are created. My code is listed below but it just does not work for the 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');
            }

        }
    });
};
like image 971
Frank Avatar asked Jul 04 '26 00:07

Frank


1 Answers

It looks like you need the jQuery .on handler.

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

The key to understanding why your code didn't work is that click will only work for currently selected set of elements on the page and 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');
            }

        }
    });
};
like image 171
filype Avatar answered Jul 05 '26 15:07

filype