I have a function which dynamically creates an element and attaches a click event to this new element.
In the current state of my app, this function is called 5 times: for the 4 first created elements, all works fine, but the 5th one has no event attached!
I insist: I'm not merely saying that click doesn't work: Using $._data(myElemn,'events')
in the console, I get Object { click=[1]}
returned for the 4 working elements, but "undefined" for the last one.
Here is the code.
But I don't think is where the problem lies: since it works for other elements, It seems that the difference should come from the particular context of the 5th element.
So my question is rather: can we imagine which particular conditions may cause and event not to be attached (obviously,without any error message).
var createDDT= function(element) { /*
---------
Creates a drop-down toggle button embedded into element.
*/
$(element).css({position:'relative'}) // (relative: since DDT pos is absolute)
.append(
$('<span \/>').addClass(DDT)
.css({display:'none',})
.append($('<span \/>'))
// when click, toggle submenu:
.click(function(event) {
// hide or show current %Submenu:
var submenu=$(event.target).closest('li').find(jqSUBMENU);
submenu.toggleClass(OPEN);
// hide any other %Open %Submenu:
$(jqOPEN).not(submenu).removeClass(OPEN);
setTimeout(liveWidthDisplay,_params.cssTimeout); // adjust LWD's position
return false; // avoid following link, if embedded in <a>
})
);
}
[EDIT] As I previously said, the issue resides probably outside of the function. To emphasize it, in my app I tried replacing the code by the following:
var createDDT= function(element) { /*
---------
Creates a drop-down toggle button embedded into element.
*/
$(element).css({position:'relative'}) // (relative: since DDT pos is absolute)
.append(
$('<span \/>').addClass(DDT)
.css({display:'none',})
.append($('<span \/>'))
// when click, toggle submenu:
.click(function(event) {
alert(event.target.id);
})
);
}
Then the result is unchanged: $._data(myElem,'events')
returns "undefined".
Unfortunately, I can't realistically add a significant context into jsFiddle, since it is a huge app.