3

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');
            }

        }
    });
};
Shaunak D
  • 19,751
  • 9
  • 41
  • 72
Frank
  • 73
  • 1
  • 1
  • 5

1 Answers1

1

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');
            }

        }
    });
};
Filype
  • 6,921
  • 7
  • 36
  • 60
  • You are my hero. Can you explain the logic behind why just a regular click function does not work? – Frank May 02 '15 at 04:20
  • 1
    I edited the question to explain, your code didn't work because `click` will only work for currently selected set of elements on the page and not future ones – Filype May 02 '15 at 05:50
  • 1
    Initially, when you setup your click handler, there were 3 buttons (for example) on the page, so event handler was attached to only those 3 existing buttons. Here is more info about https://learn.jquery.com/events/event-delegation/ – geekychick May 02 '15 at 06:57