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');
}
}
});
};
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');
}
}
});
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With