This question already has an answer here:
I've been having a lot of trouble attaching the click event to a JQuery object before adding it to the DOM.
Basically I have this button that my function returns, then I append it to the DOM. What I want is to return the button with its own click handler. I don't want to select it from the DOM to attach the handler.
My code is this:
createMyButton = function(data) {
var button = $('<div id="my-button"></div>')
.css({
'display' : 'inline',
'padding' : '0px 2px 2px 0px',
'cursor' : 'pointer'
}).append($('<a>').attr({
//'href' : Share.serializeJson(data),
'target' : '_blank',
'rel' : 'nofollow'
}).append($('<image src="css/images/Facebook-icon.png">').css({
"padding-top" : "0px",
"margin-top" : "0px",
"margin-bottom" : "0px"
})));
button.click(function () {
console.log("asdfasdf");
});
return button;
}
The button that is return is unable to catch the click event. However, if I do this (after the button is added to the DOM):
$('#my-button').click(function () {
console.log("yeahhhh!!! but this doesn't work for me :(");
});
It works... but not for me, not what I want.
It seems to be related to the fact that the object is not yet a part of the DOM.
Oh! By the way, I'm working with OpenLayers, and the DOM object that I'm appending the button to is an OpenLayers.FramedCloud (Which is not yet a part of the DOM but will be once a couple of events are triggered.)
You have to append it. Create the element with:
Then if you append it will work.
Take a look at your example here and a simple version here.
jQuery .on method is used to bind events even without the presence of element on page load. Here is the link It is used in this way:
Before jquery 1.7, .live() method was used, but it is deprecated now.
Try this.... Replace body with parent selector
Try:
jsfiddle example.
When using .on() and binding to a dynamic element, you need to refer to an element that already exists on the page (like body in the example). If you can use a more specific element that would improve performance.
Src: http://api.jquery.com/on/