I'm making a code where I add content dynamically by appending an ul element.
The thing is that if I click the dynamically created button called savePalette it doesn't work.. Although it does work for the first one, because I define the addPalette function before the click function..
From what I have read, .on() is supposed to work in these cases where dynamic content is added.
This is the HTML Structure:
JavaScript:
function addPalette() {
var defaultColors = ["#00c4ff", "#00a6ff", "#0091ff", "#007bff"];
$("ul.palettes").append("" +
"- " +
" " +
"
");
$("li.paletteGroup:last").hide();
for(var i = 1; i <= 4; i++) {
var j = (4 - i);
$("ul.palettes li.paletteGroup:last ul").prepend("");
}
$("li.paletteGroup").show("fade", 500);
}
And then this at the top of the script tag
addPalette();
$("button[name=savePalette]").on("click", function() {
alert("Heeeeej");
});
Answer
You have to put the selector for the dynamic element in the selector argument:
$("ul.palettes").on("click", "button[name=savePalette]", function() {
alert("Heeeej");
});
No comments:
Post a Comment