Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Click() doesn't work when clicking a <li> in an <ul>

Tags:

jquery

Trying to click an item in a dynamically-generated list, but the $.click() function just won't fire.

HTML for the list:

<div>
    <ul id="site_list"> </ul>
</div>

jQuery to generate the list (which works as intended, generating a long list of data with the desired class attribute):

var sites =[];
    $.getJSON("php/ABC.php", function(result){
        $.each(result.Sites, function(i,v){
            sites.push('<li class="site" id="site_'+ ABC + '</li>');
        });

        $('#site_list').append(sites.join(''));
    });

jQuery to be triggered when clicking a list (doesn't work...it doesn't throw errors...just fails to respond. I've tried $('#site') as well, to no avail. I suspect it's due to the method I'm using to generate the <ul>...something is preventing the DOM from properly recognizing each element inside the UL.:

$('li').click(function(){
    $(this).toggleClass("site_selected");
});
like image 998
Ben Bernards Avatar asked Dec 20 '25 11:12

Ben Bernards


1 Answers

$('#site_list').on('click', 'li', function(){
    $(this).toggleClass("site_selected");
});

As you're addling li dynamically so you need delegate event handler to li.


Note

Delegate event structure of .on() is like following:

$(container).on(eventName, target, handlerFunction)

Here container point to a Static-element that contains the target element and belongs to DOM at page load.

like image 184
thecodeparadox Avatar answered Dec 22 '25 02:12

thecodeparadox



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!