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:
<ul class="palettes">
<li class="paletteGroup">
<ul>
<li class="colorpalette" style="background-color: #00c4ff;"></li>
<li class="colorpalette" style="background-color: #00a6ff;"></li>
<li class="colorpalette" style="background-color: #0091ff;"></li>
<li class="colorpalette" style="background-color: #007bff;"></li>
<li class="paletteControls">
<button name="savePalette" class="savePalette">Save</button>
<button name="changeName" class="changeName">Change Name</button>
</li>
</ul>
</li>
</ul>
JavaScript:
function addPalette() {
var defaultColors = ["#00c4ff", "#00a6ff", "#0091ff", "#007bff"];
$("ul.palettes").append("<li class=\"paletteGroup\"><ul>" +
"<li class=\"paletteControls\"><button name=\"savePalette\" class=\"savePalette\">Save</button>" +
"<button name=\"changeName\" class=\"savePalette\">Change Name</button></li>" +
"</li></ul></li>");
$("li.paletteGroup:last").hide();
for(var i = 1; i <= 4; i++) {
var j = (4 - i);
$("ul.palettes li.paletteGroup:last ul").prepend("<li class=\"colorpalette\" style=\"background-color:" + defaultColors[j] + "\"></li>");
}
$("li.paletteGroup").show("fade", 500);
}
And then this at the top of the script tag
addPalette();
$("button[name=savePalette]").on("click", function() {
alert("Heeeeej");
});