I have this problem, but in short: I have a self calling function (function TCC() {...})(); that generates two sections of elements, among other things. These elements are generated with the class btn. Another JQuery function of $('.btn').click(function () {...}; [with an appropriate console.log() ] is showing that all elements on the page with class btn are being clicked except the two aforementioned sections’ elements.
One comment suggests “The issue occurs because you bind the click event, before the “column button generator” loop.”, and a suggested solution of:
$.each(cols, function(i) {...}).done(function(){ //Add click event handler now });
First question is can someone elaborate on ‘because you bind the click event, before the “column button generator” loop.’
Second question is about the proposed solution. Since I have two separate lines of code for generation, and the $('btn').on('click', function() {...}); block is over 50 lines, how do implement a solution without duplicating the lines of code, as I would assume the .done() method would require this. The page in question is here.
-
The current scope structure of the generation code relative to the
.on('click')is as follows (sorry for pic, but StackOverflow didn’t like the formatting for some reason):
Does the scope of the generation lines of code effect this, and if so, can I pull them out of the self calling function to fix the ‘bind to click event’ the suggestion spoke of?
I appreciate your help and expertise, as learning programming from scratch, these types of structure lessons are often left out of the online learning tools often included in textbooks.
You really should’ve posted the actual code. But no matter. I think the only issue why your
clickevents are not being called, is that you’ve used an incorrect syntax.The on function of jQuery, has the following syntax –
HTML
JavaScript
Since the
onfunction basically replaces theliveanddelegatefunctions, the handler is now defined for all buttons indiv.buttons, irrespective of when and how it was created (meaning dynamically created). This can be bit misleading.If you do a simple select of the sort
jQuery assumes that you are talking about direct event binding – i.e, the dom element is already loaded. It won’t affect any dynamically created elements (mind you, if you attach the bindings after the creation code, it will still work on those elements, as they are already present in the DOM).
Unless you provide the second selector, this the default behavior. This is a bit confusing, but moving on. If you want to target those elements before actually creating them, do something of this sort