Here is my dynamically generated lists :
<ul class="config-swatch-list">
<li class='color' onclick="color_select();">
<a href="#" style="background-color: random_val"></a>
</li>
<li class='color' onclick="color_select();">
<a href="#" style="background-color: random_val"></a>
</li>
<li class='color' onclick="color_select();">
<a href="#" style="background-color: random_val"></a>
</li>
<li class='color' onclick="color_select();">
<a href="#" style="background-color: random_val"></a>
</li>
<li class='color' onclick="color_select();">
<a href="#" style="background-color: random_val"></a>
</li>
</ul>
and the js function:
function color_select() {
$('#color').click(function()
{
if ($(this).hasClass('active')) {
console.log('clicked');
$(this).removeClass('active');
} else {
$(this).addClass('active');
}
});
}
My problem is using this code when I clicked 1st li
element, this js function add a active
class successfully . But this does not work for 2nd, or 4th li
element (printing clicked
in console).So the codes only working for 1st, 3rd , and 5th li
elements. If I double click 2nd or 4th li
element then the code working as expected.
All I want to do is after a click change a single li
element css class to active
or remove active
class if there is already existing active
class.